1

I am having this weird problem in Android Studio wherein my program cannot parse the String I am matching through regex.

private Pattern myPattern = Pattern.compile("([Request ID:]+)(\\d+)([, BY:]+)(\\d+)([ ])([A-Z\\d ]+)([ ])([amount:]+)(\\d+(\\.\\d{1,2}))");

     msg = "Request ID:22, BY:123414045601 DEALER01 amount:100.00 | Request ID:41, BY:123414012341 DEALER01 amount:100.00 | Request ID:2, BY:123414032110 DEALER MAKER5 amount:500.00";

    String[] items = msg.split("\\|");
    for(int i = 0; i <items.length; i++){

        Matcher match = pendingPattern.matcher(items[i]);
        if (!match.matches()) {

        } else {

            list1.add(match.group(2));
            list2.add(match.group(4));
            list3.add(match.group(9));
        }
    }

My regex matches "Request ID:2, BY:123414032110 DEALER MAKER5 amount:500.00" but doesnt match the other entries. I have already checked this on regex101.com and all of my entries matches there.

Your insight about this is greatly appreciated.

1 Answer 1

1

It is because of spaces before and after | in your input.

You can use String.trim() to get rid of it like:

Matcher match = pendingPattern.matcher(items[i].trim());

Or else don't let spaces appear in split array by using this regex in split:

String[] items = msg.split("\\s*\\|\\s*");
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! This solved my problem. I didn't thought that the white spaces have such an impact.

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.