[英]Regex - How to recognize a String + white spaces + String
I need to recognize some pattern which goes like this: 我需要认识到一些这样的模式:
[letters][some spaces][letters] [信件] [一些空格] [信件]
What I done so far is this: 到目前为止我做的是:
String regex = "[a-zA-Z]\\s+[a-zA-Z]";
As per the requirement, you wrote letters (with a s at the end). 根据要求,你写了字母 (最后用s )。
[letters][some spaces][letters]
So to do that you must be quantifying the character class as 所以要做到这一点,你必须量化字符类
String regex = "[a-zA-Z]+\\s+[a-zA-Z]+";
[a-zA-Z]+
Matches one or more letters. [a-zA-Z]+
匹配一个或多个字母。 Here +
is the quantifier which quantifies [a-zA-Z]
One or more times. 这里
+
是量化[a-zA-Z]
一次或多次的量词。
Where as if you write [a-zA-Z]\\\\s+[a-zA-Z]
, it would only match a single character before and after the space. 就像你写
[a-zA-Z]\\\\s+[a-zA-Z]
,它只匹配空格前后的单个字符。
If you want the entire string to follow this pattern, you must be adding anchors as well to the pattern as 如果您希望整个字符串遵循此模式,则必须将锚点添加到模式中
String regex = "^[a-zA-Z]+\\s+[a-zA-Z]+$";
^
Anchors the regex at the start of the string. ^
在字符串的开头处锚定正则表达式。 $
Anchors the regex at the end of the string. $
在字符串末尾锚定正则表达式。 ^
number of letters occure, [a-zA-Z]+
followed by space and again letters. ^
出现字母数量, [a-zA-Z]+
后跟空格和字母。 The second group of letters is followed by end of string $
$
结尾
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.