justDrink
justDrink

Reputation: 43

How to split special char with regex in Java

If have the following string:
MAC 1 USD14,IPHONE4 1-2-3-4 USD22,USD44,USD66,USD88

Then I would like to generate the following output:
1,1,2,3,4

I am using (\\bUSD\\d{1,99})(\\bMAC)(\\bIPHONE\\d) to split it but it doesn't work.

What should I do?

Upvotes: 0

Views: 41

Answers (1)

TheLostMind
TheLostMind

Reputation: 36304

Don't use split(). Use Pattern and Matcher to extract strings. It will be easier.

public static void main(String[] args) {
    String s = "MAC 1 USD14,IPHONE4 1-2-3-4 USD22,USD44,USD66,USD88<br>";
    Pattern p = Pattern.compile("(?<=\\s|-)\\d(?=\\s|-)"); // extract a single digit preceeded and suceeded by either a space or a `-`
    Matcher m = p.matcher(s);
    while (m.find()) {
        System.out.println(m.group());
    }

}

O/P :

1
1
2
3
4

Note : Pattern.compile("\\b\\d\\b"); will also give you the same answer.

EDIT : (?<=\\s|-)\\d(?=\\s|-)" :

(?<=\s|-) --> positive look-behind. Looks for a digit (\d) preceeded by either a space or a - (i.e, dash).

(?=\s|-) --> positive look-ahead. Looks for a digit (\d) followed by either a space or a - (i.e, dash).

Note that look-behinds / look-aheads are matched but not captured

Upvotes: 1

Related Questions