2

我有一种情况,我只需要数字和破折号,比如 2007-24。我知道如何使用正则表达式来替换数字,但是除了数字之间的破折号之外,你将如何对所有字母进行正则表达式。

输入:“CLOSED ORD NO 2007-24”

re.sub("[/-/^0-9/-]", '', self.text, flags=re.M)
4

1 回答 1

0

You may use

re.sub(r'(\d+-\d+)|.', r'\1', self.text, flags=re.S)

See the regex demo

Regex details

  • (\d+-\d+) - Group 1: one or more digits, -, 1+ digits
  • | - or
  • . - any one char

The \1 is a backreference to the Group 1 value (to keep it in the result).

See Python demo:

import re
s = "CLOSED ORD NO 2007-24"
print( re.sub(r"(\d+-\d+)|.", r'\1', s, flags=re.S) )
# => 2007-24
于 2020-07-05T09:09:54.277 回答