如何使用 Python 3 正则表达式模块获取以下字符串的 123
部分?
....XX (a lot of HTML characters)123
这里的...
部分表示一个由HTML字符、单词和数字组成的长字符串。
数字123
是XX
的特征。因此,如果有人可以建议一种通用方法,其中 XX
可以是任何字母,如 AA
或 AB
,那将会更有帮助。
旁注:
我想到使用 Perl 的 \G
运算符,首先识别字符串中的 XX
,然后识别出现在 XX
之后的第一个数字。但似乎 \G
运算符在 Python 3 中不起作用。
我的代码:
import re
source='abcd XX blah blah 123 more blah blah'
grade=str(input('Which grade?'))
#here the user inputs XX
match=re.search(grade,source)
match=re.search('\G\D+',source)
#Trying to use the \G operator to get the location of last match.Doesn't work.
match=re.search('\G\d+',source)
#Trying to get the next number after XX.
print(match.group())
最佳答案
描述
此正则表达式将匹配字符串值 XX
可以用用户输入替换。正则表达式还需要 XX
字符串被空格包围或在示例文本的开头,以防止意外的边缘情况 XX
在 EXXON
之类的词中找到.
(?<=\s|^)\b(xx)\b\s.*?\s\b(\d+)\b(?=\s|$)
代码示例:
我对 python 的了解不够深,无法提供合适的 python 示例,因此我提供了一个 PHP 示例来简单地展示正则表达式如何工作以及捕获的组
<?php
$sourcestring="EXXON abcd XX blah blah 123 more blah blah";
preg_match('/(?<=\s|^)\b(xx)\b\s.*?\s\b(\d+)\b(?=\s|$)/im',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>
$matches Array:
(
[0] => XX blah blah 123
[1] => XX
[2] => 123
)
如果您需要实际的字符串位置,那么在 PHP 中看起来像
$position = strpos($sourcestring, $matches[0])
关于Python 3 正则表达式最后一场比赛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16996150/