0

So I have a string X1X2X3\\\\. I only want to capture the AlphaNumerics values. My regex is ([A-z0-9]*).*. But it will return X1X2X3\\. My code looks like this:

Pattern pattern = Pattern.compile("([A-z0-9]*).*");
Matcher matcher = pattern.matcher(str);
matcher.matches();
return matcher.group(1);

Would like to find regex Answer. Not String.replaceAll() or replace() :)

Mihkel L.
  • 1,543
  • 1
  • 27
  • 42

1 Answers1

1

The problem is with A-z in [A-z0-9], which can match non-alpha characters as well, namely the code points between Z and a.

The correct expression to use is [A-Za-z0-9] for alphanumeric characters, or the predefined character class \\w.

(credit goes to all those who pointed out the mistake in comments)

Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43