Rodent
Rodent

Reputation: 1818

How do I check a whole existing regular expression for a digit?

I have written a regular expression as follows:

"^[\+]{0,1}([\#]|[\*]|[\d]){1,15}$"

In summary this matches an optional '+' sign followed by up to 15 characters which might be '#', '*' or a digit.

However, this means that '+#' will match and this is not a valid result as I always need at least one number.

Typical valid matches might be:

+1234
445678999
+#7897897
+345764756#775

So, given that I've crafted a valid RegEx for these to match, I guess the elegant solution is to use this regex and add some special criterion to globally check for a digit in the result OR somehow disallow anything which doesn't have at least one digit in.

How do I check for that digit?

Upvotes: 2

Views: 119

Answers (4)

Abdul Rehman
Abdul Rehman

Reputation: 1794

This should work in your case:

^(\+{0,1}[\d#]{1,15})$

Demo: https://regex101.com/r/fU1eC2/1

Edit:

If you need # after + in string use ^[+#]?([\d#]{1,15})(?<!#)$ matches "+#7897897"

If don't, use ^[+#]*([\d#]{1,15})(?<!#)$ matches "+#7897897"

Upvotes: -2

Stephan
Stephan

Reputation: 43013

Try this regex (my first idea initially):

^(?=.*[0-9])[+]?([#*\d]{1,15})$

Regular expression visualization

You can replace [0-9] with \d.

DEMO:

https://regex101.com/r/bM9oE6/3

Upvotes: 5

Toto
Toto

Reputation: 91385

I'd use

^(?=.*\d)\+?[#*\d]{1,15}$

Explanation:

^               : begining of line
  (?=           : lookahead
    .*\d        : at least one digit
  )
  \+?           : optional +
  [#*\d]{1,15}  : 1 to 15 character in class [#*\d]
$               : end of line

matched:

+1234
445678999
+#7897897
+345764756#775
###456

not matched:

+#*
+*
#*
+#

Upvotes: 2

Giuseppe Ricupero
Giuseppe Ricupero

Reputation: 6272

This solutions requires at least one digit in the string, using lookahead (the (?=...) section):

^(?=.*\d)\+?[#*\d]{1,15}$

Legenda

^               # Start of the string (or line with m/multiline flag)             
  (?=.*\d)      # Lookahead that checks for at least one digit in the match
  \+?           # An optional literal plus '+'
  [#*\d]{1,15}  # one to fifteen of literal '#' or '*' or digit (\d is [0-9])
$               # End of the string (line with m/multiline flag)

Online Demo

Regex graphical schema (everybody loves it)

Regular expression visualization

NOTE: as you can see in the demo avoid also combinations just like +* or + or #* , you get it...

Upvotes: 5

Related Questions