简体   繁体   中英

Python 3 Regex Last Match

How do I grab the 123 part of the following string using Python 3 regex module?

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

Here the ... Part denotes a long string consisting of HTML characters, words and numbers.

The number 123 is a characteristic of XX . So if anybody could suggest a universal method in which XX can be any letters like AA or AB , it would be more helpful.

Side Note:
I thought of using Perl's \\G operator by first identifying XX in the string and then identifying the first number appearing after XX . But it seems \\G operator doesn't work in Python 3.

My code:

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())

Description

This regex will match the string value XX which can be replaced with the user input. The regex will also require that the XX string be surrounded by white space or at the beginning of your sample text which prevents the accidental edge case where XX is found inside a word like EXXON .

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

在此输入图像描述

Code Example:

I don't know python well enough to offer a proper python example, so I'm including a PHP example to simply show how the regex would work and the captured groups

<?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
)

If you need the actual string position, then in PHP that would look like

$position = strpos($sourcestring, $matches[0]) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM