Regular Expression in Java

4

I'm programming in Java and need to filter a String from a regex using the matches() method.

I can accept letters (a-z) or numbers (0-9), where this number can have 1 or n digits. I'm using the following regex: [A-Z|a-z|\d{n} ] .

The filter of the letters is working perfectly, but the one of the numbers is not accepting a number with more than one digit ( 10 for example), whereas numbers of a single digit are passing. I do not know much about regex, but from what I read, this should work.

    
asked by anonymous 07.06.2014 / 03:01

1 answer

5

When you use square brackets on a regex, you are asking her to match one and only one character from the indicated list. Except for the special characters ( - , \ and ^ [at start]), everything inside the brackets is interpreted literally. This means that regex:

[A-Z|a-z|\d{n} ]

Will accept the strings:

"A"
"B"
"Z"
"|"
"4"
"{"
"}"
" "

And will reject any string with more than one character. If you want a regex that matches two or more rules combined with or ( | ), you have to do this outside the square brackets:

([A-Z]|[a-z]|\d{n})

or simplifying:

([A-Za-z]|\d{n})

Note: You say "1 or n digits", but in this case it would accept exactly n digits. If what you want is even 1 or n, this should work:

([A-Za-z\d]|\d{n})

Assuming that n is a number. But on a second reading, it seems to me that what you want is "one or more digits," would that be? If it is, the correct one is:

([A-Za-z]|\d+)

Example in ideone .

P.S. In Java, parentheses are optional when using | , since each

07.06.2014 / 03:22