我试图用Java编写一个正则表达式,该正则表达式获取所有两位数字(两位数字不能以0开头),并且它之前没有字符,后面跟着字符。
例如,我希望在以下字符串中匹配数字30:
但不想在以下几个方面:
我正在尝试使用查找来完成这一任务,而到目前为止我所取得的最接近的结果是:(?<!\w)(1[2-9]|[2-9][0-9])(?!([\w]))
两位数不能以0开头,我不想在三位数内匹配2位数。
发布于 2017-02-23 15:46:27
您可以使用以下正则表达式:
(?<!\S)[1-9]\d(?!\d)|(?<!\d)[1-9]\d(?!\S)在定义Java字符串文本的regex模式时,请记住双反斜杠。
模式匹配:
(?<!\S) -下一个数字之前必须加上空格或字符串的开头。[1-9]\d -从1到9的数字,然后任意一个数字(?!\d) -两位数字不能跟在另一个数字后面| -或(?<!\d) -在.[1-9]\d -数字从1到9,然后任意一位数(?!\S) --应该在后面加上空格或字符串的末尾。发布于 2017-02-22 21:42:30
下面的代码简单地用Java测试Wiktor的注释:
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestIt
{
public static void main (String args[])
throws Exception
{
String test1 = "character30 wordstart";
String test2 = "wordstart 30character";
String test3 = "the number 30 is here";
String failTest = "character30character";
String regex = "\\b\\d{2}|\\d{2}\\b";
Pattern pat = Pattern.compile(regex);
Matcher match = pat.matcher(test1);
System.out.println("test1: " + match.find());
match = pat.matcher(test2);
System.out.println("test2: " + match.find());
match = pat.matcher(test3);
System.out.println("test3: " + match.find());
match = pat.matcher(failTest);
System.out.println("failTest: " + match.find());
}
}取得的成果:
test1: true
test2: true
test3: true
failTest: falsehttps://stackoverflow.com/questions/42402568
复制相似问题