I am very confused on how Java's regular expressions work. I want to extract two strings from a pattern that looks like this:
String userstatus = "username = not ready";
Matcher matcher = Pattern.compile("(\\.*)=(\\.*)").matcher(userstatus);
System.out.println(matcher.matches());
But printing this will return false. I want to get the username, as well as the space that follows it, and the status string on the right of the equals sign and then store them both separately into two strings.
How would I do this? Thank you!
So the resulting strings should look like this:
String username = "username ";
String status = " not ready";
First, I assume that you are doing this as a learning exercise on regex, because a non-regex solution is easier to implement and to understand.
The problem with your solution is that you are escaping the dot, telling regex engine that you want to match literally a dot '.'
, not "any character". A simple fix to this problem is to remove \\
:
(.*)=(.*)
Demo.
This would work, but it is not ideal. A better approach would be to say "match everything except =
, like this:
([^=]*)=(.*)
Demo.
With \\.*
you are trying to match zero or many dot characters. So the expression "(\\.*)=(\\.*)"
actually expects something like ..=.
or ..=
. The wild card for any character is a simple .
. To fix your code, you can change your regular expression to "(.*)=(.*)"
. This would match as many characters as it can before the =
symbol and all the characters afterwards.
However, this solution is ugly and is not the best approach to do the job. The best thing to do is to use the split
method if you want to extract what's on the left and the right side of the =
sign.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With