我试图从字符串“左”中拉出两个字符串(表示整数,其中-999999< = i< = 999999)了。'总会有两个字符串代表两个整数。另外,我希望正则表达式与{" -1"," 2"}匹配" -1-2",而不是{" -1&#34 ;," -2"}。我已经浏览了http://www.regular-expressions.info上的教程和stackoverflow正则表达式页面,现在进行了四个小时。我正在Java程序中测试我的表达式。这就是我所拥有的
String left = "-123--4567";
Pattern pattern = Pattern.compile("-?[0-9]{1,6}");
Matcher matcher = pattern.matcher(left);
arg1 = matcher.group(1);
arg2 = matcher.group(2);
System.out.println("arg1: " + arg1 + " arg2: " + arg2);
此代码应生成
arg1: -123 arg2: -4567
答案 0 :(得分:0)
以下是您可能尝试做的事情的独立示例:
String[] examples = {
"-123--4567",
"123-4567",
"-123-4567",
"123--4567"
};
// ┌ group 1:
// |┌ zero or one "-"
// || ┌ any number of digits (at least one)
// || | ┌ zero or one "-" as separator
// || | | ┌ group 2
// || | | |┌ zero or one "-"
// || | | || ┌ any number of digits (at least one)
Pattern p = Pattern.compile("(-?\\d+)-?(-?\\d+)");
// iterating over examples
for (String s: examples) {
// matching
Matcher m = p.matcher(s);
// iterating over matches (only 1 per example here)
while (m.find()) {
// printing out group1 --> group 2 back references
System.out.printf("%s --> %s%n", m.group(1), m.group(2));
}
}
<强>输出强>
-123 --> -4567
123 --> 4567
-123 --> 4567
123 --> -4567
答案 1 :(得分:0)