如何使用regex将数字与给定单词分开?

2024-04-24 07:31:37 发布

您现在位置:Python中文网/ 问答频道 /正文

如果给定的单词被数字包围,我需要把它们分开。例如,单词是“x”。你知道吗

s = '''
1x 3    # OK
s1x2    # WRONG
2x      # OK
s1 x2   # WRONG
x2      # OK
1sx3    # WRONG
'''

print(re.sub("(?<=\d)\s*x\s*(?=\d)", " x ", s))

即使周围的数字不是一个数字,我的意思是,s1 x2s1x3x也不应该匹配。你知道吗

另一方面,它不适用于“否”-仅适用于最后两行:

s = '''
2 no 3  # OK (but it's not needed to match)
2no     # OK
3no2    # OK
no9     # OK
xno9    # WRONG
5 non   # WRONG (for 'no')
'''

print(re.sub("(?<=\d)\s*no\s*(?=\d)", " x ", s))

我编辑了一些例子。 有必要在句子中使用它,例如:

Sever land and erect 1x 3 Bedroom chalet bungalow and 1x2 bedroom bungalow. Installation of 2 non-illuminated fascia signs and 2no ad signs.

第一句话中的两个应该匹配,只有第二句话中的第二个。你知道吗

编辑

多亏了下面的帖子,我找到了匹配的:

\b(?:\d*\s*x\s*\d+|\d+\s*x\s*\d*)\b

但问题是它不适用于替代品。这个想法是为被数字包围的单词增加一个额外的空格。因此,虽然这种模式现在正确地选择了那些短语(从单行和句子中),但它不适用于替换,因为它应该只匹配那些单词:

s = "Sever land and erect 1x 3 Bedroom chalet bungalow and 1x2 Bedroom bungalow"

re.sub("\b(?:\d*\s*x\s*\d+|\d+\s*x\s*\d*)\b", " x ", s, flags=re.IGNORECASE)

Tags: andnore编辑ok数字单词句子
2条回答
data = '''
Sever land and erect 1x 3 Bedroom chalet bungalow and 1x2 bedroom bungalow. Installation of 2 non-illuminated fascia signs and 2no ad signs.
'''

cases = ['no', 'nos', 'x']

import re

l = data
for case in cases:
    l = re.sub(r'\s{2,}', ' ', re.sub(r'(?<=\d| ){}(?=\d| )'.format(case), r' {} '.format(case), l))

print(l)

印刷品:

Sever land and erect 1 x 3 Bedroom chalet bungalow and 1 x 2 bedroom bungalow. Installation of 2 non-illuminated fascia signs and 2 no ad signs.

您可以使用alternation使用^ {CD1>}来匹配任何一个所需的数字,其中^ {< CD2>}或^ {< CD3>}可以在中间匹配。你知道吗

^(?:\d* *(?:x|no)\s*\d+|\d+\s*(?:x|no) *\d*)$

Regex demo

相关问题 更多 >