Home > Back-end >  Python regular expression method [duplicate]
Python regular expression method [duplicate]

Time:09-29

Using python regular expression method, Please help in printing a field of numbers if it is between MOD and X. For example, if MOD2357X is in the string, we want 2357. This should work for any number, not just the example number.

I have used r'(?<=MOD)\d (?=X)', however it is not running for every text between "MOD" and "X".

Edit - If my input string contains MOD2357&12AB!234X - then i need all the digits as output btwn MOD and X. How can i not capture &AB! and print 235712234 as output ? This is just one of the scenario . I have to actually test all of the scenarios if i do not know the contents of the input string or how many words, sentences, or paragraphs it contains.

Edit 1 - I am curious if it is possible to get the desired output from "re.search" command as well?

CodePudding user response:

IIUC

s = 'MOD2357&12AB!234X'

num = int(''.join(re.findall(r'\d ', ''.join(re.findall(r'(?<=MOD).*(?=X)', s)))))

Output:

>>> num
235712234

CodePudding user response:

You could use ''.join() to combine the numbers into a single string. The below code would accept the string from user and extract the numbers.

import re
string = input()
numbers = "".join(re.findall(r'[0-9] ', string))
print(numbers)
  • Related