温馨提示×

正则表达式匹配非空且非null字符串该怎么写

小亿
133
2023-12-21 17:52:49
栏目: 编程语言

正则表达式匹配非空且非null字符串可以使用如下的表达式:

^(?![\s\S]*$)\S+$

解释:
`^`:匹配字符串的开始位置
`(?![\s\S]*$)`:负向零宽度断言,确保后面不全是空白字符或任意字符
`\S+`:匹配一个或多个非空白字符
`$`:匹配字符串的结束位置
示例用法:

String regex = "^(?![\\s\\S]*$)\\S+$";
String input = "abc";
boolean isMatch = input.matches(regex);
System.out.println(isMatch);  // 输出 true
input = null;
isMatch = input.matches(regex);
System.out.println(isMatch);  // 输出 false
input = "   ";
isMatch = input.matches(regex);
System.out.println(isMatch);  // 输出 false

上述正则表达式可以匹配包含至少一个非空白字符的字符串,而不匹配空字符串、空白字符串或null。

0