Java: String.matches ()

I want to determine if a string consists of two words with one space in between. The first word should contain only alphanumeric characters. The second should include only numbers. Example:asd 15

I would like to use String.matches. How can I do this or what regular expression to use?

Thanks in advance.

+3
source share
3 answers

You are looking for something like:

String regex = "^[A-Za-z]+ [0-9]+$";

Explanation:

^         the beginning of the string (nothing before the next token)
[A-Za-z]+ at least one, but maybe more alphabetic chars (case insensitive)
          a single space (hard to see :) )
[0-9]+    at least one, but maybe more digits
$         end of the string (nothing after the digits)
+7
source

You can give this regex a try.

"[A-Za-z0-9]+\\s[0-9]+"
+4
source

Try: String pattern = new String("^[0-9]*[A-Za-z]+ [0-9]+$")

0
source

All Articles