Java模式使用
情景:Java模式使用,java,regex,matcher,Java,Regex,Matcher,情景: Pattern whitespace = Pattern.compile("^\\s"); matcher = whitespace.matcher(" WhiteSpace"); Pattern whitespace2 = Pattern.compile("^\\s\\s"); matcher2 = whitespace2.matcher(" WhiteSpace"); 我正在尝试在一行的开头添加空格。我想得到空格匹配器的确切数目。我的字符串是“空白” 问题是matcher和m
Pattern whitespace = Pattern.compile("^\\s");
matcher = whitespace.matcher(" WhiteSpace");
Pattern whitespace2 = Pattern.compile("^\\s\\s");
matcher2 = whitespace2.matcher(" WhiteSpace");
我正在尝试在一行的开头添加空格。我想得到空格匹配器的确切数目。我的字符串是“空白”
问题是
matcher
和matcher2
都在处理这个字符串
我想要的是:仅获得1个空白的模式,但此模式不应工作 对于2个空白字符串。在下面的场景中,
matcher.find()
和matcher2.find()
都是真的。但是matcher.find()
应该为false,matcher2.find()
应该为true
Pattern whitespace = Pattern.compile("^\\s");
matcher = whitespace.matcher(" two whitespaces");
Pattern whitespace2 = Pattern.compile("^\\s\\s");
matcher2 = whitespace2.matcher(" two whitespaces");
if(matcher.find()==true){
//XXXXXXXXXXX
} else if(matcher2.find()==true){
//YYYYYYYYYYY
}
我希望matcher对于“WhiteSpace”
为true,对于“WhiteSpace”
(两个空格)我希望matcher2为true:
“空白”
我想做的事情是
我有一个字符串
“两个空格”
如果语句为真,则在下面两个选项中都有<代码>匹配器应为false。
matcher2
应为true
Pattern whitespace = Pattern.compile("^\\s");
matcher = whitespace.matcher(" two whitespaces");
Pattern whitespace2 = Pattern.compile("^\\s\\s");
matcher2 = whitespace2.matcher(" two whitespaces");
if(matcher.find()==true){
//XXXXXXXXXXX
} else if(matcher2.find()==true){
//YYYYYYYYYYY
}
如果您希望确保在一个空格之后没有另一个空格,但实际上不希望包含要在匹配中测试的第二个字符(无论它是否为空格),则可以使用机制
(?!…)
所以,若在行首并没有另一个空格,那个么只能和行首的空格匹配的模式可能看起来像
Pattern whitespace = Pattern.compile("^\\s(?!\\s)");
这可以按空格调整为任何数字
Pattern whitespace = Pattern.compile("^\\s{3}(?!\\s)");
如果您希望确保在一个空格之后没有另一个空格,但实际上不希望包含要在匹配中测试的第二个字符(无论它是否为空格),则可以使用机制
(?!…)
所以,若在行首并没有另一个空格,那个么只能和行首的空格匹配的模式可能看起来像
Pattern whitespace = Pattern.compile("^\\s(?!\\s)");
这可以按空格调整为任何数字
Pattern whitespace = Pattern.compile("^\\s{3}(?!\\s)");
在这里,一种模式可能是一种过度杀伤力*。使用
Character.isWhitespace
并获得更简单的代码:
String in = " your input here";
int wsPrefix=0;
for ( ; wsPrefix < in.length() && Character.isWhitespace(in.charAt(wsPrefix)) ;
wsPrefix++ ) {}
System.out.println("wsPrefix = " + wsPrefix);
String in=“您在此处的输入”;
int wsPrefix=0;
对于(;wsPrefix
*因为据说:
“有些人在遇到问题时会想
“我知道,我会使用正则表达式。”现在他们有两个问题。
--
在这里,模式可能是一种过度使用*。请使用
字符。isWhitespace
并获得更简单的代码:
String in = " your input here";
int wsPrefix=0;
for ( ; wsPrefix < in.length() && Character.isWhitespace(in.charAt(wsPrefix)) ;
wsPrefix++ ) {}
System.out.println("wsPrefix = " + wsPrefix);
String in=“您在此处的输入”;
int wsPrefix=0;
对于(;wsPrefix
*因为据说:
“有些人在遇到问题时会想
“我知道,我会使用正则表达式。”现在他们有两个问题。
--