Java - 正则表达式解析字符串

时间:2017-11-07 15:03:36

标签: java regex

尝试解析给定样本的名称

++++++++++++++++++SELIZABETH+COLLAZO+++++++++++++++++++
+++++++++++++++++++PALOMA+CORREA+++++++++++++++++++++++
+++++++++++++++++++NOAH+BLAKEMORE++++++++++++++++++++++

我已经尝试了

//++(.*?)+(.*?)//++

但那已经过去了。

想要将名字和姓氏解析为两个字符串。

1 个答案:

答案 0 :(得分:6)

您可以将此正则表达式(\w+)\+(\w+)\+{2,}(.*?)\+(.*?)\+{2,}与模式一起使用,如下所示:

String str = "++++++++++++++++++SELIZABETH+COLLAZO+++++++++++++++++++\n"
        + "+++++++++++++++++++PALOMA+CORREA+++++++++++++++++++++++\n"
        + "+++++++++++++++++++NOAH+BLAKEMORE++++++++++++++++++++++";

Pattern pattern = Pattern.compile("(\\w+)\\+(\\w+)");// or instead "\\+{2,}(.*?)\\+"(.*?)\\+{2,}
Matcher matcher = pattern.matcher(str);

while (matcher.find()) {
    System.out.println(matcher.group(1) + " " + matcher.group(2));
}

输出

SELIZABETH COLLAZO
PALOMA CORREA
NOAH BLAKEMORE