正则表达式匹配 python 中方括号中的数字
Regular Expression to match numbers in square brackets in python
我需要匹配 return 方括号中数字的字符串索引。示例字符串:
Gabrilovich and Markovitch [11, 12] propose a method to use
conditional random fields [6] as a training process.....
在这里,我想使用正则表达式提取上述情况中任何给定数字(如 11、12 或 6)的索引。我在努力
pattern = re.compile(r'[/11/]') # for 11
result = re.search(pattern, text, flags=0)
print result.start()
然而,我没有得到想要的结果。注意:我需要一个解决方案来匹配我想要的确切数字,而不是括号内的任何给定数字。
使用此正则表达式 (\[[,\d\s ]*)11([,\d\s ]*\])
检索文本中的所有 11
看看我上传的例子https://regex101.com/r/lN8mA6/1
由于在 Python 中我们不能使用标准 re
模块的可变宽度 lookbehinds,您可以使用捕获组,然后检查组的索引。
Sample code 用于捕获 11
:
pattern = re.compile(r'(\[[^\]]*)\b(11)\b(?=[^\]]*\])') # for 11
text = 'Gabrilovich and Markovitch [11, 12] propose a method to use conditional random fields [6] as a training process.....'
result = re.search(pattern, text)
if result:
print result.start(2)
结果:28
.
请注意,我在 11
周围使用单词边界来仅匹配 11
,而不匹配 111
或 112
。
试试这个正则表达式:\[\s*(\d*)(\s*,\s*(\d*)\s*)?(\s*,\s*(\d*)\s*)?(\s*,\s*(\d*)\s*)?(\s*,\s*(\d*)\s*)?(\s*,\s*(\d*)\s*)?(\s*,\s*(\d*)\s*)?\]
(重复组 (\s*,\s*(\d)\s*)?
以允许在方括号之间得到最多 7 个数字)如此 demo 所示。如果你想更笼统,你可以用 \[\s*(\d*)(\s*,\s*(\d*)\s*)*\]
替换这个正则表达式,它允许列表中的数字数量不定(但是你会得到第一个和最后一个只在组 </code> 和 <code>
)
如果您使用第一个,您将在逗号周围留出空格,您将得到第 1、3、5、7、11、13 和 15 组中的数字。
我需要匹配 return 方括号中数字的字符串索引。示例字符串:
Gabrilovich and Markovitch [11, 12] propose a method to use conditional random fields [6] as a training process.....
在这里,我想使用正则表达式提取上述情况中任何给定数字(如 11、12 或 6)的索引。我在努力
pattern = re.compile(r'[/11/]') # for 11
result = re.search(pattern, text, flags=0)
print result.start()
然而,我没有得到想要的结果。注意:我需要一个解决方案来匹配我想要的确切数字,而不是括号内的任何给定数字。
使用此正则表达式 (\[[,\d\s ]*)11([,\d\s ]*\])
检索文本中的所有 11
看看我上传的例子https://regex101.com/r/lN8mA6/1
由于在 Python 中我们不能使用标准 re
模块的可变宽度 lookbehinds,您可以使用捕获组,然后检查组的索引。
Sample code 用于捕获 11
:
pattern = re.compile(r'(\[[^\]]*)\b(11)\b(?=[^\]]*\])') # for 11
text = 'Gabrilovich and Markovitch [11, 12] propose a method to use conditional random fields [6] as a training process.....'
result = re.search(pattern, text)
if result:
print result.start(2)
结果:28
.
请注意,我在 11
周围使用单词边界来仅匹配 11
,而不匹配 111
或 112
。
试试这个正则表达式:\[\s*(\d*)(\s*,\s*(\d*)\s*)?(\s*,\s*(\d*)\s*)?(\s*,\s*(\d*)\s*)?(\s*,\s*(\d*)\s*)?(\s*,\s*(\d*)\s*)?(\s*,\s*(\d*)\s*)?\]
(重复组 (\s*,\s*(\d)\s*)?
以允许在方括号之间得到最多 7 个数字)如此 demo 所示。如果你想更笼统,你可以用 \[\s*(\d*)(\s*,\s*(\d*)\s*)*\]
替换这个正则表达式,它允许列表中的数字数量不定(但是你会得到第一个和最后一个只在组 </code> 和 <code>
)
如果您使用第一个,您将在逗号周围留出空格,您将得到第 1、3、5、7、11、13 和 15 组中的数字。