简体   繁体   中英

Java - regex parse string

Trying to parse out names with given samples

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

I've tried

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

but that's way off.

Would like to parse out the first and last name to two strings.

You can use this regex (\\w+)\\+(\\w+) or \\+{2,}(.*?)\\+(.*?)\\+{2,} with Pattern like this :

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));
}

Outputs

SELIZABETH COLLAZO
PALOMA CORREA
NOAH BLAKEMORE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM