user13074756
user13074756

Reputation: 413

Regex in Python for all nums and hyphen any where in the text

I need regex to match the below:

1. 34224-2343
2. 32423434242-23234
3. 1-324235

The hyphen can be anywhere in the string and the string will have all nums.

I have the below but it is not working:

text = "43-2765936"

if text.replace("-","") and all(char.isdigit() for char in text):
    print ('yes')

Upvotes: 0

Views: 85

Answers (2)

The fourth bird
The fourth bird

Reputation: 163362

Perhaps you could shorten it using isnumeric() on the result of first replacing - with an empty string.

text = "43-2765936"

if text.replace("-", "").isnumeric():
    print ('yes')

Output

yes

If there has to be a digit present and as most a single -, you can also use a pattern and assert for a digit to be present:

 ^(?=-*\d)\d*(?:-\d*)?$
  • ^ Start of string
  • (?=-*\d) Assert at least a single digit
  • \d* Match optional digits
  • (?:-\d*)? Optionally match - and optional digits
  • $ End of string

Regex demo

Upvotes: 2

Jan
Jan

Reputation: 43169

You need to change your code to:

text = "43-2765936"

if all(char.isdigit() for char in text.replace("-", "")):
    print ('yes')

Strings in Python are immutable and text.replace("-", "") does not change the original text variable.


To ensure that there's only one - in your string use some logic:

text = "43-2765936"
cleaned = text.replace("-", "", 1)

if "-" in text and cleaned.isnumeric():
    print("yes")

Or a regular expression altogether:

^(?=[^-]*-[^-]*$)[-\d]+$

See a demo on regex101.com.

Upvotes: 3

Related Questions