How to do this with regex

F

freddy

Hi guys,

i have a problem wirh a regular expression.

following text ist given

<some text>word1< some more text>word2<text>word3<another text>word4<
text is going on>

if want to have a match when there is word1, word2 and word4 in the
text, but between word2 and word4 there is no word3. But word3 can be
found in the text, e.g. after word4. And it could be a multilinetext
Thanks for help

Freddy
 
A

Ann

freddy said:
Hi guys,

i have a problem wirh a regular expression.

following text ist given

<some text>word1< some more text>word2<text>word3<another text>word4<
text is going on>

if want to have a match when there is word1, word2 and word4 in the
text, but between word2 and word4 there is no word3. But word3 can be
found in the text, e.g. after word4. And it could be a multilinetext
Thanks for help

Freddy
How about if you get the index position of the 4 words and figure
it out from that.
 
A

Alan Moore

if (str.matches("(?s).*?alpha.*?beta(?:(?!charlie|delta).)*+delta.*"))

Note that this regex is very inefficient, because each time it tries to
match the "." metacharacter, it first has to look ahead to make sure
that it's not at the start of one of the sentinel words. If speed
matters, you can create a much faster regex using the "anything but the
initial" technique that I suggested in the earlier "Non-greedy
backwards" thread:

String regex =
"(?:[^a]++|a(?!lpha))*+alpha" +
"(?:[^b]++|b(?!eta))*+beta" +
"(?:[^cd]++|c(?!harlie)|d(?!elta))*+delta(?s.*)";

With this regex, most characters are efficiently gobbled up by the
negated character classes; it only has to do a lookahead whenever it
sees the first letter of the next sentinal word.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,990
Messages
2,570,211
Members
46,796
Latest member
SteveBreed

Latest Threads

Top