在Java中使用Regex找出字符串中的给定单词

时间:2018-11-22 08:55:30

标签: java regex regex-group

给出一个字符串, 在Java或Java代码中使用 regex ,我必须从给定的String中找出选举人的名字:

                "K ~\n" +
                "m W swim\n" +
                "sfiaruqsr\n" +
                "wvnn 021m: r’ i\" W' _ ~\n" +
                "_ 4'“; x ‘ D\n" +
                "W ma ¢ “ii-a? “Rm qwfl\n" +
                "Electors name ; Moleslwar Moreshva;\n" +
                "Tuwal\n" +
                "mam-a #02,qu _\n" +
                "F\n" +
                "Fm“ Name : Momma! Tuppal I\n" +
                "‘ e\n" +
                "Pam sq» : w! MALE '\n" +
                "“WW/Dale m mm ; XX/xxnsae _‘"

对于给定的String,输出应为: Moleslwar Moreshva Tuwal

由于String响应每次都会更改,因此无法对任何内容进行硬编码。 请帮忙:)

1 个答案:

答案 0 :(得分:0)

没有名称结尾定界符,因此必须假定需要从存在Electors name的行和仅下一行捕获全名。捕获后,请用空格替换不需要的字符。

这是为您解析名称的Java代码,

public static void main(String[] args) {
    String s = "K ~\n" +
            "m W swim\n" +
            "sfiaruqsr\n" +
            "wvnn 021m: r’ i\" W' _ ~\n" +
            "_ 4'“; x ‘ D\n" +
            "W ma ¢ “ii-a? “Rm qwfl\n" +
            "Electors name ; Moleslwar Moreshva;\n" +
            "Tuwal\n" +
            "mam-a #02,qu _\n" +
            "F\n" +
            "Fm“ Name : Momma! Tuppal I\n" +
            "‘ e\n" +
            "Pam sq» : w! MALE '\n" +
            "“WW/Dale m mm ; XX/xxnsae _‘";

    Pattern p = Pattern.compile("Electors name\\s*;\\s*([\\w; ]+\\n\\w+)");
    Matcher m = p.matcher(s);
    if (m.find()) {
        System.out.println(m.group(1).replaceAll(";\\n", " "));
    } else {
        System.out.println("Didn't match");
    }
}

这将打印以下输出,

Moleslwar Moreshva Tuwal