1

There are several questions about this but non answered my question. I wish to use pattern and matcher to find a pattern in a string and then from there create a list out of the matches that include the rest of the not match as well.

 String a = "125t160f"; // The "t" could be replaced with symbols such as "." or anything so I wish to take one of anything after many digits.
 Matcher m = Pattern.compile("(\\.?\\d+\\.)").matcher(a);
 System.out.println(m.find());

My current result:

False

My expected result should be in list:

["125t", "160f"] // I understand how to do it in python but not in java. So could anyone assist me in this.

1 Answer 1

1

Your pattern should be \d+\D:

String a = "125t160f";
Matcher m = Pattern.compile("\\d+\\D").matcher(a);
while (m.find()) {
    System.out.println(m.group(0));
}

The above regex pattern says to match one or more digits, followed by a single non digit character. If we can't rely on a non digit character to know when to stop matching, then we would need to know how many digits to consume.

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

7 Comments

Thank you but it didnt give me the rest of the string and not in list form. Is there a way to do so? When I tried re.findall in python, it will return me ["125t", "160t"] the second element is usually the rest of the remaining string.
and also this pattern will not work if we take chinese character after the digit. For example, "125空". Then it will not take the "空".
I have answered your question. If you want to match Chinese numeric characters, then you will have to build your own regex character class for that.
The one you showed me is to take the same pattern even for the remaining string. It is not taking the whole remaining string. But thank you. For example, "125t126tttttttttt"
Then use the pattern \d+\D+.
|

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.