Python 3 正则表达式最后一场比赛

标签 python regex string parsing python-3.x

如何使用 Python 3 正则表达式模块获取以下字符串的 123 部分?

....XX (a lot of HTML characters)123

这里的...部分表示一个由HTML字符、单词和数字组成的长字符串。

数字123XX 的特征。因此,如果有人可以建议一种通用方法,其中 XX 可以是任何字母,如 AAAB,那将会更有帮助。

旁注:
我想到使用 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字符串被空格包围或在示例文本的开头,以防止意外的边缘情况 XXEXXON 之类的词中找到.

(?<=\s|^)\b(xx)\b\s.*?\s\b(\d+)\b(?=\s|$)

enter image description here

代码示例:

我对 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/

相关文章:

python - 使用 .loc 和多个条件从 DataFrame 中选择行,然后显示与一列的最小值/最大值对应的行

python - 有没有不同的方法来检查 python 中的双端队列是否为空

python - 比较文件中的值 python

java - String.split 是如何工作的?

python - 将 "stamp"字符串转换为所需字符串的最佳方法

java - 将 Character[] 的范围转换为 String

python - session.credentials()对于在AWS中设置连接如何有用?

java - 关于Java中正则表达式的问题

c++ - 为什么 c++11 正则表达式(libc++ 实现)这么慢?

C++ _TCHAR* 到 std::string