简体   繁体   中英

Regular Expression to select substring

I have input string

DISPLAY_MSG='Kumar + sajdhjhasd - Type' 
              and  ID=156090 
              and RESOURCE_KEY='Ascend.ElementMaster.kumar_type.desc' 
              and  LOCALE='en_US'

I want to match only DISPLAY_MSG='Kumar + sajdhjhasd - Type' but using this expression

DISPLAY_MSG='[\\w\\W\\s\\S]*

matching whole string. How can I select only string between only those two single codes after

DISPLAY_MSG=

This regex is quite nonsensical.

[\\w\\W\\s\\S] means: Match a character if it is either alphanumeric or non-alphanumeric or whitespace or non-whitespace. The exact same result can be achieved by (?s). .

Only in JavaScript (where the (?s) option that allows the dot to match newlines isn't available, it makes sense to write [\\s\\S] instead. But [\\w\\W\\s\\S] is definitely overkill.

So, a better solution using lazy quantifiers would be

DISPLAY_MSG='(?s).*?'

But even better would be to actually specify what is allowed between the quotes, and that usually is anything but a quote:

DISPLAY_MSG='[^']*'

You should try using non-greedy quantifier to reduce the match to smallest possible length.

RegEx: Smallest possible match or nongreedy match

Following is a good example http://www.exampledepot.com/egs/java.util.regex/greedy.html

You should use ungreedy quantifier. Try this:

DISPLAY_MSG='[\\w\\W\\s\\S]*?'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM