[英]The Java Pattern and Matcher Regex curiosity
最近,我在正則表達式上做了很多編碼。 我一直假設模式一直這樣(代碼sample1),直到我像代碼sample2一樣嘗試了它:
代碼示例1
Pattern pattern = Pattern.compile("^([\\w]+)(?=\\s)|(?<=\\*)(.+?)(?=\\)|$)");
Matcher matcher = pattern.matcher(word);
String sub1 = null;
String sub2 = null;
while (matcher.find()) {
if (matcher.group(1) != null) {
sub1 = matcher.group(1);
System.out.println(sub1);
}
else if (matcher.group(2) != null) {
sub2 = matcher.group(2);
System.out.println(sub2);
}
}
那很好,產生結果。 同時,當我如下圖所示更改結構時:
代碼示例2
Pattern pattern = Pattern.compile("^([\\w]+)(?=\\s)|(?<=\\*)(.+?)(?=\\)|$)");
Matcher matcher = pattern.matcher(word);
//note please, though I have taken out the String definition it still gives the same result even If I had defined them here like I did in code1
while (matcher.find()) {
String sub1 = matcher.group(1);
String sub2 = matcher.group(2);
System.out.println(sub1);
System.out.println(sub2);
}
我意識到有時sub1為null,有時sub2為null。 關於Matcher內部運作的任何清晰簡潔的解釋?
您的第一個代碼示例等效於以下內容:
Pattern pattern = Pattern.compile("^([\\w]+)(?=\\s)|(?<=\\*)(.+?)(?=\\)|$)");
Matcher matcher = pattern.matcher(word);
while (matcher.find()) {
String sub1 = matcher.group(1);
String sub2 = matcher.group(2);
if(sub1 != null) System.out.println(sub1);
else if(sub2 != null) System.out.println(sub2);
}
基本上,當您引用的組(在這種情況下為1
或2
)在搜索字符串中沒有對應位置時, Matcher.group
返回null
。
第一個示例通過使用if(... != null)
檢查來保護println
語句,從而防止null
的輸出,此代碼示例也可以使用第二個示例的樣式來完成檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.