我有一个操作,处理许多空格分隔的字符串,我正在寻找字符串匹配函数的正则表达式,如果第一个空格之前的前两个字符串以大写字母开头,将触发pass,如果不是,将返回false。
示例:
"AL_RIT_121 PA_YT_32 rit cell 22 pulse"
将返回true,因为前两个子串AL_RIT_121
和PA_YT_32
分别以大写字母A
和P
开头
"AL_RIT_252 pa_YT_21 mal cell reg 32 1 ri"
将返回false,因为p
为小写。
发布于 2012-11-19 17:11:06
简单的string.matches("[A-Z]\\w+ [A-Z].*")
发布于 2012-11-19 17:10:36
Pattern.compile("^\\p{Lu}\\S*\\s+\\p{Lu}")
将使用.find()
方法。没有理由在前缀测试中使用matches
,但是如果有外部约束,只需这样做
Pattern.compile("^\\p{Lu}\\S*\\s+\\p{Lu}.*", Pattern.DOTALL)
要分解它,请执行以下操作:
^
匹配字符串的开头,\\p{Lu}
匹配任何大写字母,\\S*
匹配零个或多个非空格字符,包括_
\\s+
匹配一个或多个空格字符,\\p{Lu}
匹配第二个单词开始的大写字母。在第二个变体中,结合使用.*
和Pattern.DOTALL
来匹配输入的其余部分。
发布于 2012-11-19 17:15:15
如果这两个示例演示了您的输入格式,则可以使用特定的正则表达式:
^(?:[A-Z]+_[A-Z]+_\d+\s*)+
这意味着:
^ - Match the beginning of the string
(?: - Start a non-capturing group (used to repeat the following)
[A-Z]+ - Match one or more uppercase characters
_ - Match an underscore
[A-Z]+ - Match one or more uppercase characters
_ - Match an underscore
\d+ - Match one or more decimals (0-9)
\s* - Match zero or more space characters
)+ - Repeat the above group one or more times
在Java中,您可以像这样使用它:
Pattern pattern = Pattern.compile("^(?:[A-Z]+_[A-Z]+_\\d+\\s*)+");
Matcher matcher = p.matcher( inputString);
if( matcher.matches()) {
System.out.println( "Match found.");
}
https://stackoverflow.com/questions/13458723
复制相似问题