簡體   English   中英

Java 正則表達式非空字符串

[英]Java Regex non-empty string

我想斷言該名稱不為空。 我正在使用以下正則表達式

"(?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)

\\S匹配任何單個非空白字符。 請注意,它也可以匹配"字符,如果鍵值之間沒有空格,則修復這一點很重要。

您可以將\\\\S替換為[^\\\\s\\"]+並將最后的.*?替換為.* (后者是出於性能原因):

String regex = "(?s).*?\"name\":\"[^\\s\"]+\".*";

請參閱正則表達式演示 詳情

  • (?s) - 嵌入標志選項等於Pattern.DOTALL
  • .*? - 任何零個或多個字符,盡可能少
  • \\"name\\":\\" - 文字"name":"文本
  • [^\\s"]+ - 除了空格和"之外的一個或多個字符
  • " - 一個"字符
  • .* - 字符串的其余部分(因為.現在匹配任何字符,由於(?s) )。

很明顯,您正在使用需要整個字符串匹配的matches().*? 一開始就證明了這一點。 但是,模式開始處的任何點模式都會使匹配變慢,尤其是對於較長的模式(您的不是)和長文本(從探針描述中不清楚)。 通過使用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 演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM