Extracting numbers from a string under certain conditions

Viewed 277

I have some strings that are stored in a dataframe using pandas and I want to extract all numbers out of them if it exists. The conditions these numbers must meet are quite specific and I'm not really sure if I can use regex to solve my problem. The conditions are:

  • The number CANNOT be at the start of the string
  • It CANNOT appear after the word "No. " or after the word "Question "

Also if possible, if the number has an e right after it I would want to keep that as well. However this is less important.

This is what I have so far to find all the numbers, but I do not know how to code the conditions I mentioned above.

testNumbers = re.findall(r'\d+', row['Name'])

For a given string: " Test T860 Article No. 9712250 787"

I would want the regex expression to return

[860, 787]
2 Answers

You may use

(?!^)(?<!\d)(?<!\bNo\.\s)(?<!\bQuestion\s)(\d+)(?!\d)

In Python, declare as a raw string literal:

pattern = r'(?!^)(?<!\d)(?<!\bNo\.\s)(?<!\bQuestion\s)(\d+)(?!\d)'

See the regex demo

Details

  • (?!^) - not at the start of the string
  • (?<!\d) - no digit immediately before the current location is allowed
  • (?<!\bNo\.\s) - no No. and a whitespace immediately before is allowed
  • (?<!\bQuestion\s) - no Question and a whitespace immediately before is allowed
  • (\d+) - Group 1: one or more digits
  • (?!\d) - no digit immediately after the current location is allowed.

In Pandas, you may use it like

df = pd.DataFrame({'text':[" Test T860 Article No. 9712250 787"," Test F199 Article Question 9712250787"]})
df['numbers'] = df['text'].str.findall(r'(?!^)(?<!\d)(?<!\bNo\.\s)(?<!\bQuestion\s)(\d+)(?!\d)').apply(','.join)

Output:

>>> df
                                     text  numbers
0       Test T860 Article No. 9712250 787  860,787
1   Test F199 Article Question 9712250787      199

Here we can use an expression with word boundaries and quantifier:

\b[A-Z]+(\d+)\b|\b([0-9]{1,3})\b

Demo

RegEx

If this expression wasn't desired or you wish to modify it, please visit regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Related