0

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?

2
  • you need single digit integer or multiple? Commented Apr 30, 2015 at 3:56
  • @MohanRaj hi, i need single digit Commented Apr 30, 2015 at 4:23

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Could you explain the pattern you have used here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.