nfinium
nfinium

Reputation: 141

Java Regex Negate certain word

I need some help creating a regular expression.
I need to get all the words between the first keyword and the last keyword.

Assume the first keyword is All and the last keyword is At.

Sample Input:

All abc abcd abcccc abdd At

The output must be:

abc abcd abccc abdd

This is my current regex right now:

(\\s*All (\\w|\\s)+( At))

My problem is that if ever the input is like this:

All abc abc abc abc abc At At

The output is:

abc abc abc abc abc At

Upvotes: 2

Views: 327

Answers (2)

user unknown
user unknown

Reputation: 36269

Shorten your String before:

String toSearchFor = source.substring (source.indexOf ("All"), source.indexOf ("At")+"At".length);

However, I'm not sure what to do with

"At At All abc At All def All ghi At jkl At At All"

Upvotes: 0

rodion
rodion

Reputation: 15029

Try non-greedy matching for the words in the middle:

(\s*All (\w|\s)+?( At))

Note the added ? sign. This should tell regex engine to return the shortest match for the (\w|\s)+ part, hopefully yielding the result you need.

Upvotes: 3

Related Questions