简体   繁体   中英

extract a string with regex

I'm a beginner using regex, I have Strings like String1= "DELIVERY 'text1' 'text2'" and string2="DELIVERY 'text1'" , I want to extract "text1" . I tried this pattern

 Pattern p = Pattern.compile("^DELIVERY\\s'(.*)'");
 Matcher m2 = p.matcher(string);

                if (m2.find()) {

                    System.out.println(m2.group(1));

                    }

the result was : text1' 'text2 for the 1st string and text1 for the second i tried this too

Pattern p = Pattern.compile("^DELIVERY\\s'(.*)'\\s'(.*)'");
Matcher m2 = p.matcher(string);

                    if (m2.find()) {

                        System.out.println(m2.group(1));

                        }

it return a result only for String1

Your first attempt was almost right. Just replace:

.*

With:

.*?

This makes the operator "non-greedy", so it will "swallow up" as little matched text as possible.

Your regex .* is "greedy", and consumes as much input as possible yet still match, so it will consume everything from the first to the last quote.

Instead use a relictant version by adding ? , ie .*? to costume as little as possible yet still match, which won't skip iver a quote.

Combine this change with some java Kung Fu and you can do it all in one line:

String quoted = str.replaceAll(".*DELIVERY\\s'(.*?)'.*", "$1");

if you only want to have 'text1' , try this regex:

"DELIVERY '([^']*)"

or without grouping:

"(?<=DELIVERY ')[^']*"

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