[英]Extract a sub string from a string using regular expression
給定以下Java代碼:
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);
我想提取''
所有內容,例如我想要'abc,ab,123'
和'123,aa,abc'
。 為什么出局是:
false
我的正則表達式是這樣的:“找到一個'
,后跟一個數字或字母,后跟幾個非空格字符,后跟另一個'
”。 應該有一場比賽,怎么了?
Matcher.matches
將嘗試檢查正則表達式是否可以匹配整個字符串(請參見此處的文檔)。 由於您的正則表達式期望在末尾加上'
,但字符串的最后一個字符為,
匹配返回false。
如果要打印與正則表達式匹配的字符串的一個或多個部分,則需要首先使用Matcher.find方法,以使正則表達式引擎將該匹配的子字符串本地化。 要獲取下一個匹配的子字符串,您可以從同一Matcher中再次調用find
。 要獲取所有匹配的子字符串,請調用find
直到它返回false
作為響應。
嘗試:
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.