1

I need a regular expression to match a string that is not a string of numbers. Given my limited knowledge about regexes, I assume that .* means any number of characters that matches the following reg expressions.

Therefore, I thought this would work:

.*[\\D]

But unfortunately it didn't. Instead this works:

.*[\\D].* 

Can anyone explain to me or at least point to me where i can understand this? The java website and most website that I found is not simple enough.

peterh
  • 11,875
  • 18
  • 85
  • 108
user3300845
  • 127
  • 2
  • 11

2 Answers2

0

The point '.' means everything, this could be a number, or any character or symbol. The star '*' indicates the amount, it means it can appear as much as it wants, zero till infinity. The '\D' means a non number.
So in your first regex, the string has to end with a non number.

123blablub -> match
blablub123 -> no match

In your second regex the non digit is followed by any character which appears zero or more times. In words: your second regex matches with every string that includes one or more non digits.

123blablub -> match
blablub123 -> match
Stephan
  • 15,704
  • 7
  • 48
  • 63
0

. matches any character.

* is a quantifier that matches the previous token any number of times, including 0.

Therefore .* matches any number of any characters.

[] denotes a character class. Any character in the class is allowed. For example, [abc] matches a or b or c once.

\D is a character class of non-digits. (You need to escape the \ as it is also a special character in Java string literals.) You can combine character classes in character classes so [\D] is valid, though it's shorter to write it as just \D.

Essentially what the regex you have is: begin with any number of any characters, followed by one non-digit, followed by any number of any characters. That's essentially the same as saying there must be at least one non-digit.

laalto
  • 150,114
  • 66
  • 286
  • 303