我想斷言該名稱不為空。我正在使用以下正則運算式
"(?s).*?\"name\":\"\\S\".*?"
適用于以下輸入:
[{"id": 12,"name":"t","gender":"male"} (return is not empty)
[{"id": 12,"name":"","gender":"male"} (return is empty)
當名稱包含多個如下字符時不起作用
[{"id": 12,"name":"to","gender":"male"} (returns is empty)
uj5u.com熱心網友回復:
\S匹配任何單個非空白字符。請注意,它也可以匹配"字符,如果鍵值之間沒有空格,則修復這一點很重要。
您可以\\S用[^\\s\"] 和 last.*?替換.*(后者是出于性能原因):
String regex = "(?s).*?\"name\":\"[^\\s\"] \".*";
請參閱正則運算式演示。詳情:
(?s)- 嵌入標志選項等于Pattern.DOTALL.*?- 任何零個或多個字符,盡可能少\"name\":\"-文字"name":"文本[^\s"]- 除空格之外的一個或多個字符和""- 一個"字符.*- 字串的其余部分(.由于 ,現在匹配任何字符(?s))。
很明顯,您使用的 withmatches()需要整個字串匹配,.*?一開始就證明了這一點。但是,模式開始處的任何點模式都會使匹配變慢,尤其是對于較長的模式(您的不是)和長文本(從探針描述中不清楚)。通過使用Matcher#find()和"name":"[^\s"] "模式轉向部分匹配是有意義的:
//String text = "[{\"id\": 12,\"name\":\"to\",\"gender\":\"male\"}"; // => There is a match
String text = "[{\"id\": 12,\"name\":\"\",\"gender\":\"male\"}"; // => There is no match
Pattern p = Pattern.compile("\"name\":\"[^\\s\"] \"");
Matcher m = p.matcher(text);
if (m.find()) {
System.out.println("There is a match");
} else {
System.out.println("There is no match");
}
請參閱Java 演示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/342779.html
