Regular expression to match text between two closest words

Could you help me with a regex to match text between the two closest words?

For example:

text KEYWORD1 text KEYWORD1 text KEYWORD2 text KEYWORD2

The result should be:

KEYWORD1 text KEYWORD2

This does not work, which is predictable:

(KEYWORD1).*(KEYWORD2)

Is it possible to do this with regular expression? If so, how will it work with a state machine?
Java regexp syntax would be best. Thank you in advance!

+4
source share
3 answers

Update:

String val="text KEYWORD1 text KEYWORD1 text KEYWORD2 text KEYWORD2";
String REGEX="KEYWORD1((.(?!KEYWORD1))+?)KEYWORD2";
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(val);
if(matcher.find()){
    System.out.println(matcher.group());
}

See how it works:

enter image description here

Explanation:

1st capture group ((.(?!KEYWORD1))+?)

Second capture group (.(?!KEYWORD1))+?

Quantifier ( +?): between one and unlimited time, as little as possible, expanding if necessary [lazy]

. . , ,

. ( ) (?!KEYWORD1) Lookahead - , KEYWORD1 KEYWORD1 ( ) KEYWORD2 KEYWORD2 ( )

+6

:

String myString =
    "text KEYWORD1 text KEYWORD1 text KEYWORD2 text KEYWORD2";
Pattern pattern = Pattern.compile("KEYWORD1((.(?!KEYWORD1))+?)KEYWORD2");
Matcher matcher = pattern.matcher(myString);
String word = "";
if (matcher.find())
    word = matcher.group(1);

// word => " text "

.

+1

All Articles