Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex - How to get spaces and characters?

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";
like image 260
Mayron Avatar asked Feb 09 '23 15:02

Mayron


2 Answers

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.

like image 78
Sergey Kalinichenko Avatar answered Feb 16 '23 02:02

Sergey Kalinichenko


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.

like image 30
Ivaylo Toskov Avatar answered Feb 16 '23 03:02

Ivaylo Toskov