Using regex to remove all text after the last number in a string

后端 未结 2 2016
有刺的猬
有刺的猬 2021-01-25 00:25

Sample Text

1234 Main St Smallville, KS 92348Small County 

Should yield:

1234 Main St Smallville, KS 92348

Sa

2条回答
  •  无人及你
    2021-01-25 01:03

    Find the last digit in the string and then remove all the characters after it with re.sub:

    import re
    address = "1234 Main St Smallville, KS 92348Small County "
    address = re.sub(r'(\d)\D+$', r'\1', address)
    print(address) # => 1234 Main St Smallville, KS 92348
    

    See the IDEONE demo

    The regex matches and captures into Group 1 a digit (with (\d)) and then matches one or more characters other than a digit (\D+) up to the end of the string ($). The replacement pattern is a mere \1, a backreference to the digit we captured with Group 1 (to restore it in the resulting string).

提交回复
热议问题