簡體   English   中英

Python 3正則表達式最后一場比賽

[英]Python 3 Regex Last Match

如何使用Python 3 regex模塊獲取以下字符串的123部分?

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

這里...部分表示由HTML字符,單詞和數字組成的長字符串。

數字123XX的特征。 因此,如果有人可以建議一種通用的方法,其中XX可以是任何字母,如AAAB ,它會更有幫助。

邊注:
我想通過首先在字符串中識別XX然后識別出現在XX之后的第一個數字來使用Perl的\\G運算符。 但似乎\\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字符串被空格包圍或在示例文本的開頭處,以防止在像EXXON這樣的單詞內找到XX的意外邊緣情況。

(?<=\\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]) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM