捕获特定单词后括号中的单词和数字
Capturing words and number in parenthesis after a specific word
我正在使用正则表达式从这个 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?我想抓取关键字后面的三到四个字,得到整数值
好的,如果我理解问题你可以使用下面的
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)
这将 return ['10']
。
How to get the number 10 from the above line? I want to capture three to four words after the keyword and get the integer value
因此,我了解到您希望在关键字 (=of ten percent
) 和 整数 [=47] 之后得到 三到四个字=] 值 (=10
)。我假设 "keyword" 是 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 组:一个或多个单词字符,然后是 1+ 个空格的 2 或 3 个序列,后跟 1+ 个单词字符
\s*
- 0+ 个空格
\(
- 一个 (
(\d+)
- 第 2 组:一个或多个数字。
如果字数可以大于2或3或可以为1或0,则将{2,3}
替换为*
。
如果数字也可以是浮点数,请将 \d+
替换为 \d[\d.]*
。
我正在使用正则表达式从这个 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?我想抓取关键字后面的三到四个字,得到整数值
好的,如果我理解问题你可以使用下面的
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)
这将 return ['10']
。
How to get the number 10 from the above line? I want to capture three to four words after the keyword and get the integer value
因此,我了解到您希望在关键字 (=of ten percent
) 和 整数 [=47] 之后得到 三到四个字=] 值 (=10
)。我假设 "keyword" 是 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 组:一个或多个单词字符,然后是 1+ 个空格的 2 或 3 个序列,后跟 1+ 个单词字符\s*
- 0+ 个空格\(
- 一个(
(\d+)
- 第 2 组:一个或多个数字。
如果字数可以大于2或3或可以为1或0,则将{2,3}
替换为*
。
如果数字也可以是浮点数,请将 \d+
替换为 \d[\d.]*
。