Zachary Loughridge
Zachary Loughridge

Reputation: 177

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.

Upvotes: 0

Views: 203

Answers (1)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60046

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

Upvotes: 5

Related Questions