我想创建一个只在两个字符串之间有空格的正则表达式(即我的名字是xyz),不允许只包含空格()的字符串。
我正在尝试这个:
Pattern patt = Pattern.compile("[[a-zA-Z0-9.,_-]+[' ']+[a-zA-Z0-9.,_-]+]*");
但它也需要" "作为有效的输入。
请帮我解决这个问题
答案 0 :(得分:2)
使用此Pattern
:
"[\\w.,-]+\\s+[\\w.,-]+"
答案 1 :(得分:1)
您可以使用否定"环顾四周。
例如:
String[] input = {"foo bar", "nope", " "};
Pattern p = Pattern.compile("(?!<\\s|^)\\s+(?!\\s|$)");
for (String s: input) {
Matcher m = p.matcher(s);
System.out.printf("Found in %s? %b%n", s, m.find());
}
<强>输出强>
Found in foo bar? true
Found in nope? false
Found in ? false
答案 2 :(得分:1)
试试这个正则表达式:
Pattern patt = Pattern.compile("[\\w.,_-]+([\\s]+[\\w.,_-]+)*");
这将检查至少一个带有允许字符的字符串,然后检查一个或多个用空格分隔的字符串。
答案 3 :(得分:0)
一个简单的正则表达式将帮助您。您只需要检查字符串的开头。
public static void main(String[] args) {
String s1 = "my name is xyz";
String s2 = " ";
// screw everything else. Does my string start with a letter, a digit,._ etc?
System.out.println(s1.matches("^[\\w\\d.,-_].*"));
System.out.println(s2.matches("^[\\w\\d.,-_].*"));
}
O / P:
true
false