简体   繁体   中英

Java Regex non-empty string

I want to assert that name is not empty. I am using the following regex

"(?s).*?\"name\":\"\\S\".*?"

Works for the following Input:

[{"id": 12,"name":"t","gender":"male"}  (return is not empty)
[{"id": 12,"name":"","gender":"male"}    (return is empty)

Does not work when name has more than one characters like the following

[{"id": 12,"name":"to","gender":"male"}  (returns is empty)

\\S matches any single non-whitespace char. Note it can also match a " char, and that is important to fix if there are no whitespaces between the key-values.

You can replace \\\\S with [^\\\\s\\"]+ and last .*? with .* (this latter is for performance reasons):

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

See the regex demo . Details :

  • (?s) - embedded flag option equal to Pattern.DOTALL
  • .*? - any zero or more chars, as few as possible
  • \\"name\\":\\" - literal "name":" text
  • [^\\s"]+ - one or more chars other than whitespace and "
  • " - a " char
  • .* - the rest of the string to the end (as . matches any char now, due to (?s) ).

It is clear you are using with matches() that requires an entire string match, .*? at the start proves this. However, any dot pattern at the pattern start makes matching slower, especially with longer patterns (yours is not) and with long texts (this is not clear from the probem description). It makes sense to turn to partial matching by using Matcher#find() and a "name":"[^\\s"]+" pattern:

//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"); 
}

See the Java demo .

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