重复正则表达式模式

时间:2015-04-11 11:20:50

标签: python regex

我正在尝试编写一个正则表达式来匹配给定字符串中的数字,下面设法检索字符串中的第一个数字,但它停在那里,我希望它匹配文件中的所有数字, 提前谢谢

正则表达式:

([^\s+\w+\n\r]*(\d))+

string:

hi there this is 1
yes this is 2

实际匹配:1 理想匹配:1,2

3 个答案:

答案 0 :(得分:0)

"([\d]+)"g

样品

test 13231 test 123123
123 asdfasdf 
1a2a3 a

将匹配

MATCH 1
1.  [5-10]  `13231`
MATCH 2
1.  [16-22] `123123`
MATCH 3
1.  [23-26] `123`
MATCH 4
1.  [37-38] `1`
MATCH 5
1.  [39-40] `2`
MATCH 6
1.  [41-42] `3`

和解释

"([\d]+)"g
    1st Capturing group ([\d]+)
        [\d]+ match a single character present in the list below
            Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
            \d match a digit [0-9]
    g modifier: global. All matches (don't return on first match)

答案 1 :(得分:0)

为什么不使用\d+简化?

请参阅demo on regex101.com/#python

答案 2 :(得分:0)

在网站regex101.com/#python上,在表达式右侧框中输入g。此框称为修饰符。正如其他人在评论中提到的那样,在python中使用re.findall(pattern, your_string)。另请注意,您实际上正在寻找两个子串 - 在正则表达式中有两对括号。