check whether the match is found using re.search() for exapmles below

Viewed 33

I want to extract numbers from strings that do not start with order and cart and that should not end with dollar.

I have the following code:

import re
pattern = "(^.*\b(?:cart|order)\b.*)(\b\d{2,12}\b)"
text1 = ('the cart number is 1234 and 4567 that it!')
text2 = ("order number note down 12345")
text3 = "credit card is 0000 and 3456"
text4 = "the 4567"
text5 = "i got 245 dollar"

result = re.search(pattern, text4)
print(result)

Expected output match

text3 0000 3456
text4 4567

Can we achieve expected output by passing one example at a time using re module?

1 Answers

You can do that with two regexps, one will check if there is a cart or order at the start with an optional article or dollar at the end, and another will extract the numbers:

import re
pattern = re.compile( r"\b\d{2,12}\b" )
pattern_valid = re.compile( r"^\s*(?:(the|an?)\s+)?(cart|order)\b|\bdollar\s*$", re.I )
texts = ['the cart number is 1234 and 4567 that it!', 
    "order number note down 12345",
    "credit card is 0000 and 3456",
    "the 4567",
    "i got 245 dollar"]
for text in texts:
    if not pattern_valid.search(text):
        print(text, pattern.findall(text), sep=" => ")

See the Python demo. Output:

credit card is 0000 and 3456 => ['0000', '3456']
the 4567 => ['4567']

The ^\s*(?:(the|an?)\s+)?(cart|order)\b|\bdollar\s*$ regex matches an optional the or a/an article at the start followed with the word order or cart or the word dollar at the end of string. If there is a match, the string is not processed. If there is no match, the second regex extracts all 2-12 digit numbers that are whole words from the string.

Related