regex - python return matching and non-matching patterns of string -
i split string parts match regexp pattern , parts not match list.
for example
import re string = 'my_file_10' pattern = r'\d+$' # know matching pattern can obtained : m = re.search(pattern, string).group() print m '10' # final result should following ['my_file_', '10']
put parenthesis around pattern make capturing group, use re.split()
produce list of matching , non-matching elements:
pattern = r'(\d+$)' re.split(pattern, string)
demo:
>>> import re >>> string = 'my_file_10' >>> pattern = r'(\d+$)' >>> re.split(pattern, string) ['my_file_', '10', '']
because splitting on digits @ end of string, empty string included.
if ever expect one match, @ end of string (which $
in pattern forces here), use m.start()
method obtain index slice input string:
pattern = r'\d+$' match = re.search(pattern, string) not_matched, matched = string[:match.start()], match.group()
this returns:
>>> pattern = r'\d+$' >>> match = re.search(pattern, string) >>> string[:match.start()], match.group() ('my_file_', '10')
Comments
Post a Comment