[英]Python 3 Regex Last Match
如何使用Python 3 regex模塊獲取以下字符串的123
部分?
....XX (a lot of HTML characters)123
這里...
部分表示由HTML字符,單詞和數字組成的長字符串。
數字123
是XX
的特征。 因此,如果有人可以建議一種通用的方法,其中XX
可以是任何字母,如AA
或AB
,它會更有幫助。
邊注:
我想通過首先在字符串中識別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.