如何识别字符串 "x-ring closing10.00x10.00mm" 中的 x 并将其替换为 space
How can I recognize the x in the string "x-ring closing10.00x10.00mm" and replace it with a space
晚上好,
我正在尝试编写一个脚本来识别字符串中的尺寸(例如:10x10x12 或 25X35X4 G)并自动将 x 替换为白色 space。因此结果将是 10 10 12 或 25 35 4。
我正在搜索的字符串将包含更多信息,其中还可以包含不应替换的 x。
我不知道如何实现这一目标,希望有人知道我如何解决这个问题。
使用 re
模块中的正则表达式。
import re
def repl_dim(m):
return " ".join(m.groups())
s = "some xXx dim: 10x10x12, 25X35X4"
print re.sub("(\d+)x(\d+)x(\d+)", repl_dim, s, flags=re.IGNORECASE)
打印
some xXx dim: 10 10 12, 25 35 4
检查 x
前面是否有数字在您的情况下应该足够了:
import re
print(re.sub("(?<=\d)x", " ", "foox barx 10x10x12"),re.I)
foox barx 10 10 12
这将替换 x/X 如果后面跟着一个数字。
>>> s = '1x2X3, 10x10x12, 25X35X4 G, XXX expert, 3x world champ, great x2'
>>> import re
>>> re.sub(r'(?<=\d)x(?=\d)', ' ', s, flags=re.I)
'1 2 3, 10 10 12, 25 35 4 G, XXX expert, 3x world champ, great x2'
您可以使用带有回顾和反向引用的正则表达式:
>>> import re
>>> s = 'x-ring closing10.00x10.00mm'
>>> s2 = 'x-ring closing10.00x10.00x5.00mm'
>>> s3 = 'dimensions 1 x 4 x3'
>>> re.sub(r'((?<=\d))\s*[xX]\s*(\d)', r' ', s)
'x-ring closing10.00 10.00mm'
>>> re.sub(r'((?<=\d))\s*[xX]\s*(\d)', r' ', s2)
'x-ring closing10.00 10.00 5.00mm'
>>> re.sub(r'((?<=\d))\s*[xX]\s*(\d)', r' ', s3)
'dimensions 1 4 3'
这将找到 "a number, possible whitespace, then x
, possible whitespace, then a number" 的实例并将它们替换为 "that first number, a space, then the second number."
# remove x that is between ints or floats
st = "10.10x10.101 44x33 bxb x199"
st = re.sub(r'(\d+(\.\d+)?)x(\d+(\.\d+)?)',r' ',st)
print(st)
10.10 10.101 44 33 bxb x199
晚上好,
我正在尝试编写一个脚本来识别字符串中的尺寸(例如:10x10x12 或 25X35X4 G)并自动将 x 替换为白色 space。因此结果将是 10 10 12 或 25 35 4。
我正在搜索的字符串将包含更多信息,其中还可以包含不应替换的 x。
我不知道如何实现这一目标,希望有人知道我如何解决这个问题。
使用 re
模块中的正则表达式。
import re
def repl_dim(m):
return " ".join(m.groups())
s = "some xXx dim: 10x10x12, 25X35X4"
print re.sub("(\d+)x(\d+)x(\d+)", repl_dim, s, flags=re.IGNORECASE)
打印
some xXx dim: 10 10 12, 25 35 4
检查 x
前面是否有数字在您的情况下应该足够了:
import re
print(re.sub("(?<=\d)x", " ", "foox barx 10x10x12"),re.I)
foox barx 10 10 12
这将替换 x/X 如果后面跟着一个数字。
>>> s = '1x2X3, 10x10x12, 25X35X4 G, XXX expert, 3x world champ, great x2'
>>> import re
>>> re.sub(r'(?<=\d)x(?=\d)', ' ', s, flags=re.I)
'1 2 3, 10 10 12, 25 35 4 G, XXX expert, 3x world champ, great x2'
您可以使用带有回顾和反向引用的正则表达式:
>>> import re
>>> s = 'x-ring closing10.00x10.00mm'
>>> s2 = 'x-ring closing10.00x10.00x5.00mm'
>>> s3 = 'dimensions 1 x 4 x3'
>>> re.sub(r'((?<=\d))\s*[xX]\s*(\d)', r' ', s)
'x-ring closing10.00 10.00mm'
>>> re.sub(r'((?<=\d))\s*[xX]\s*(\d)', r' ', s2)
'x-ring closing10.00 10.00 5.00mm'
>>> re.sub(r'((?<=\d))\s*[xX]\s*(\d)', r' ', s3)
'dimensions 1 4 3'
这将找到 "a number, possible whitespace, then x
, possible whitespace, then a number" 的实例并将它们替换为 "that first number, a space, then the second number."
# remove x that is between ints or floats
st = "10.10x10.101 44x33 bxb x199"
st = re.sub(r'(\d+(\.\d+)?)x(\d+(\.\d+)?)',r' ',st)
print(st)
10.10 10.101 44 33 bxb x199