简体   繁体   中英

Extract a sub string from a string using regular expression

Given the following Java codes:

String test = "'abc,ab,123',,,'123,aa,abc',,,";
Pattern p = Pattern.compile("('\\w\\S+\')");
Matcher m = p.matcher(test);
boolean s = m.matches();
System.out.println(s);

I want to extract all the content in '' , for example I want 'abc,ab,123' and '123,aa,abc' . Why the outout is:

false

My regular expression is like: "find a ' ,followed by a number or a letter, followed by several non-space characters,followed by another ' ". It should have a match, what's wrong?

Matcher.matches will try to check if regex can match entire string (see the documentation here ). Since your regex expects ' at the end, but your string last character is , matches returns false.
If you want to print one or more part of string which matches your regex you need to use Matcher.find method first to let regex engine localize this matching substring. To get next matching substring you can call find again from the same Matcher. To get all matching substrings call find until it returns false as response.

Try:

String test = "'abc,ab,123',,,'123,aa,abc',,,";
Pattern p = Pattern.compile("'[^']*'");//extract non overlapping string between single quotes
Matcher m = p.matcher(test);
while (m.find()) { //does the pattern exists in input (sub)string
  System.out.println(m.group());//print string that matches pattern
}

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