【问题标题】:Capturing words and number in parenthesis after a specific word捕获特定单词后括号中的单词和数字
【发布时间】:2018-04-26 06:57:18
【问题描述】:

我正在使用正则表达式从 interest at the rate of ten percent (10%) 中使用关键字“interest at the rate”查找值

我试过了

re.compile(r'interest at the rate\s+((?:\w+(?:\s+|$)){3})').findall(r.decode('utf-8'))

并获得['of ten percent ']

现在,我试过了

re.compile(r'interest at the rate of\s+((?:\w+(?:\s+|$)){3})').findall(r.decode('utf-8'))

但是,我得到的只是一个空值,[]

如何从上面的行中得到数字 10?我想在关键字后面捕获三到四个单词并获取整数值。

【问题讨论】:

标签: python regex keyword matching


【解决方案1】:

如何从上面的行中得到数字 10?我想在关键字后面捕获三到四个单词并获取整数值

所以,我知道您希望在关键字 (=of ten percent) 和整数 值 (=10) 之后得到三到四个字。我假设“关键字”是interest at the rate,正是您在模式中使用的。

那么,你可以使用

import re
s = "interest at the rate of ten percent (10%)"
r = re.compile(r'interest at the rate (\w+(?:\s+\w+){2,3})\s*\((\d+)')
print(r.findall(s))
# => [('of ten percent', '10')]

请参阅Python demo

详情

  • interest at the rate - 关键字
  • (\w+(?:\s+\w+){2,3}) - 第 1 组:一个或多个单词字符,然后是 2 或 3 个 1+ 空格序列,后跟 1+ 单词字符
  • \s* - 0+ 个空格
  • \( - 一个(
  • (\d+) - 第 2 组:一位或多位数字。

如果字数可以超过 2 或 3 或可以为 1 或 0,请将 {2,3} 替换为 *

如果数字也可以是浮点数,请将\d+ 替换为\d[\d.]*

【讨论】:

  • 感谢您的详细解释
【解决方案2】:

好的,如果我理解了你的问题,你可以使用下面的

import re

value = "interest at the rate of ten percent (10%)"
regexString = r"^interest at the rate of ten percent \(([0-9]{2})%\)$"

result = re.findall(regexString, value, 0) # Zero is the flag for match all, you can omit this. 

print(result)

这将返回['10']

【讨论】:

  • 遗憾的是,上述代码仅适用于 2 位数字。我想为所有数字工作,比如 7%..
  • 在这种情况下,只需删除限制,即使用^interest at the rate of ten percent \(([0-9]+)%\)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-03
相关资源
最近更新 更多