How to extract proper string from text by ignoring the special character preceding the string?

Viewed 59

I have couple of text from where I have to extract string followed by specific word but I am facing an issue where the special character(it can be any special character) are preceded by the string.Please correct my regex to get correct result:
Here are some pasted text samples Sample 1:
"customer no �123456"
Sample 2:
"customer id %9999999"
Sample 3:
"customer id 12121212"
Sample 4:
"customer id @134563"

I want the following output of above text samples:
Sample 1 output:
"123456"
Sample 2 output:
"9999999"
Sample 3 output:
"12121212"
Sample 4 output:
"134563"

The regex I have used giving wrong output:
r'\bcustomer\s(?:id|no)\s+(\w+)'

Please help me correct my regex to get proper output.

1 Answers

You can use \W to match any non-word char (mostly, any char other than a letter, digit or underscore):

r'\bcustomer\s(?:id|no)\W+(\w+)'

See the regex demo

Details

  • \b - a word boundary
  • customer - a string
  • \s - a whitespace (add + after \s to match any one or more whitespace chars)
  • (?:id|no) - id or no substring
  • \W+ - one or more chars other than word chars (letters/digits/underscores)
  • (\w+) - Group 1: one or more word chars.
Related