试图确定正确的正则表达式

时间:2016-06-15 01:43:18

标签: java regex

我正在使用Java并且有一个String,sum,其内容将是这样的:

A bunch of miscellaneous text
A bunch more miscellaneous text
Handicap Accessible *value*
More miscellaneous Text
Even more miscellaneous text 

值可以是是,否

我试图用正则表达式获取值的值。我不能只执行sum.replaceAll("^.*Handicap Accessible ",""),因为"."中有新行和其他字符不计算。

我正在尝试使用正则表达式,但我无法正确使用它。以下是我尝试过的,有和没有反斜杠。请注意,这是来自java所以我需要使用两个反斜杠(\\):

    Pattern pat = Pattern.compile("Handicap Accessible \\([A-Za-z]*\\)");
    Matcher match = pat.matcher(sum);
    String newAccess = null;
    while (match.matches()) {
        newAccess = match.group(1);
        break;
    }

但是当我打印newAccess的值时,它总是为空。如果我将newAccess初始化为其他类似“GLUB”的内容,那么“GLUB”就是最后打印的内容,这意味着没有输入匹配循环。

有关使用正确模式的任何建议吗?

3 个答案:

答案 0 :(得分:1)

我会选择(接受@Tim的回答,感谢蒂姆):

String input = "A bunch of miscellaneous text\n" +
           "A bunch more miscellaneous text\n" +
           "Handicap Accessible None\n" +
           "Handicap Accessible Yes\n" +
           "More miscellaneous Text\n" +
           "Handicap Accessible No\n" +
           "Handicap Accessible somevalue\n" +
           "Even more miscellaneous text\n";
Pattern p = Pattern.compile("^Handicap Accessible (Yes|None|No)$", Pattern.MULTILINE);
Matcher m = p.matcher(input);
while ( m.find() ){
    System.out.println( "Value is: " + m.group(1) );
}

根据@Qix的建议,我从Handicap Accessible (Yes|None|No)更改为"^Handicap Accessible (Yes|None|No)$", Pattern.MULTILINE,它在多行文字中效果更好(而不只是\n

我将输出:

Value is: None
Value is: Yes
Value is: No

答案 1 :(得分:0)

将match.matches()替换为match.find():

Pattern pat = Pattern.compile("Handicap Accessible ([A-Za-z]*)");
Matcher match = pat.matcher(sum);
String newAccess = null;
while (match.find()) {
    newAccess = match.group(1);
    break;
}

Difference between matches() and find() in Java Regex可以看出它们之间的差异。同时," \\("意味着你的模式需要匹配角色"("。

答案 2 :(得分:0)

嗯,我认为这很简单。只需应用正则表达式并打印捕获组中的内容:

    String input = "A bunch of miscellaneous text\n" +
                   "A bunch more miscellaneous text\n" +
                   "Handicap Accessible None\n" +
                   "More miscellaneous Text\n" +
                   "Even more miscellaneous text\n";

    String regex="Handicap Accessible\\s+(Yes|No|None)";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input);   
    String value=null;
    if (matcher.find()) {
        value=matcher.group(1);
    } else {
        throw new RuntimeException ("your regex is wrong dude!");
    }
    System.out.println(value);