Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
744 views
in Technique[技术] by (71.8m points)

regex - How to non-greedy multiple lookbehind matches

Source:    <prefix><content1><suffix1><prefix><content2><suffix2>
Engine:    PCRE

RegEx1:    (?<=<prefix>)(.*)(?=<suffix1>)
RegEx2:    (?<=<prefix>)(.*)(?=<suffix2>)

Result1:   <content1>
Result2:   <content1><suffix1><prefix><content2>

The desired result for RegEx2 is just <content2> but it is obviously greedy. How do I make RegEx2 non-greedy and use only the last matching lookbehind?

[I hope I have translated this correctly from the NoteTab syntax. I don't do much RegEx coding. The <prefix>, <content> & <suffix> terms are just meant to represent arbitrary strings. Only the "<" in the "?<=" lookbehind command is significant.]

I suspect it is something simple but after too many hours of searching I'm giving up on solving it myself.

Thanks for the help

Art

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I suggest you use:

(?<=<prefix>)(((?!<prefix>).)*)(?=<suffix2>)

This makes sure that there can be no <prefix> inside the match. The complete match result will be <content2>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...