0

I have a regex to extract numbers from a given string

import re
compiled_pattern = re.compile(r'\d+')
sample = "Hello world 32"

print(compiled_pattern.findall(sample))

output:

['32']

But is it possible to return 1 if there is a number in the string and 0 otherwise? Essentially 1 if there is a match for the pattern in the string and 0 otherwise. So in this case, the op should be 1. Any suggestions would be helpful

3
  • 1
    print (1 if compiled_pattern.search(sample) else 0)? Commented Jul 8, 2021 at 3:08
  • @41686d6564 please post it as the answer and I can accept it. Commented Jul 8, 2021 at 3:12
  • 1
    You can go ahead and accept the existing answer if it helps you; that's fine :) Commented Jul 8, 2021 at 3:14

1 Answer 1

1

Yes, you can test for whether regex found the pattern or not. For example:

def match_or_not(sample):
    compiled_pattern = re.compile(r'\d+')
    match = compiled_pattern.findall(sample)
    return 1 if match else 0

for sample in ["Hello world 32", "Hello again"]:
    print(match_or_not(sample))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.