Python使用正则表达式捕获字符串中的特定模式

问题描述 投票:4回答:4

我有一个像这个'6\' 3" ( 190 cm )'的字符串,我想只使用正则表达式提取'190 cm'。我找不到合适的模式来寻找。

我试过了

string = '6\' 3" ( 190 cm )'
pattern = re.compile(r'[^\\( 0-9+ \\)]')
pattern.findall(a)

但它返回[“'”,“”,','c','m']

谢谢你的帮助!

python regex pattern-matching extract
4个回答
2
投票

表达中有太多不必要和有害的符号。

使用周围的[]使findall匹配单个字符,这解释了你得到的输出。

这需要一个完整的重新思考:转义括号,使用\d+匹配一个或多个数字,以及显式cm和空格。

创建一个只匹配数字+单位的组,使用search查找组并显示它。

import re
string = '6\' 3" ( 190 cm )'
pattern = re.compile(r'\( (\d+ cm) \)')

>>> pattern.search(string).group(1)
'190 cm'

3
投票
print re.findall(r'[0-9]+ cm',string)[0]

其中string是:

'6\' 3" ( 190 cm )'

2
投票

使用正则表达式:

import re

s = '6\' 3" ( 190 cm )'
desired_output = re.search(r'\((.*?)\)',s).group(1).lstrip()

print(desired_output)
>>> 190 cm

没有正则表达式:

s = '6\' 3" ( 190 cm )'
desired_output = s[s.find("(")+1:s.find(")")].lstrip()

print(desired_output)
>>> 190 cm

1
投票

您可以使用findall将返回的捕获组:

\(\s*([0-9]+\s*[a-z]+)\s*\)

这将匹配:

  • \(\s*匹配(和0+倍的空白字符
  • (捕获组 [0-9]+\s*[a-z]+匹配1+一个数字,0 +倍空白字符和1倍a-z(如果你想匹配字面意思,请使用cm而不是[a-z]+
  • )关闭捕获组
  • \s*\)匹配空白字符的0倍以上

regex101 demo | Python demo

例如:

import re

string = '6\' 3" ( 190 cm )'
pattern = re.compile(r"\(\s*([0-9]+\s*[a-z]+)\s*\)")
print(pattern.findall(string))
© www.soinside.com 2019 - 2024. All rights reserved.