[英]How check that string is NOT blank by java regular expression?
There is regular expression for finding blank string and I want only negation. 有查找空白字符串的正则表达式,我只想取反。 I also see this question but it does not work for java (see examples).
我也看到了这个问题,但不适用于Java(请参见示例)。 Solution also not work for me (see 3-rd line in example).
解决方案对我也不起作用(请参见示例中的第3行)。
For example 例如
Pattern.compile("/^$|\\s+/").matcher(" ").matches() - false
Pattern.compile("/^$|\\s+/").matcher(" a").matches()- false
Pattern.compile("^(?=\\s*\\S).*$").matcher("\t\n a").matches() - false
return false in both cases. 在两种情况下都返回false。
PS If something is not clear ask me questions. PS:如果不清楚,请问我问题。
UPDATED 更新
I want to use this regular expression in @Pattern annotation without creating custom annotation and programmatic validator for it. 我想在@Pattern批注中使用此正则表达式,而不为其创建自定义批注和程序验证器。 That's why I want a "plain" regexp solution without using find function.
这就是为什么我想要一个不使用find函数的“普通”正则表达式解决方案的原因。
It's not clear what you mean by negation. 否定你的意思还不清楚。
If you mean "a string that contains at least one non-blank character," then you can use this: 如果您的意思是“包含至少一个非空白字符的字符串”,则可以使用以下命令:
Pattern.compile("\\S").matcher(str).find()
If it's really necessary to use matches
, then you can do it with this. 如果确实需要使用
matches
,那么您可以这样做。
Pattern.compile("\\A\\s*\\S.*\\Z").matcher(str).matches()
This just matches 0 or more spaces followed by a non-space followed by any characters at all up to the end of the string. 这仅匹配0个或多个空格,后跟一个非空格,然后是直到字符串末尾的所有字符。
If you mean "a string that is all non-blank with at least one such character," then you can use this: 如果您的意思是“一个至少有一个这样的字符的非空白字符串”,那么您可以使用以下命令:
Pattern.compile("\\A\\S+\\Z").matcher(str).matches()
You need to study the Java regex syntax . 您需要学习Java regex语法 。 In Java, regular expressions are compiled from strings, so there's no need for special delimiters like
/.../
or %r{...}
as you'll see in other languages. 在Java中,正则表达式是从字符串编译而成的,因此不需要像其他语言中那样的特殊分隔符,例如
/.../
或%r{...}
。
How about this: 这个怎么样:
if(!string.trim().isEmpty()) {
// do something
}
使用regex
\\s
:空格字符: \\t\\n\\x0B\\f\\r
。
Pattern.compile("\\s")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.