正则表达式:拒绝比赛

时间:2018-11-14 21:12:46

标签: regex python-3.x

python 3.5 re版本2.2.1

玩具示例:

S1 = 'Arithmetic Return 2018 (%)'
s2 = 'Arithmetic Return 2019 (%)'

p = re.compile(r'(^.*?Arithm.*$)')
w = [re.findall(p, a) for a in [s1, s2]]
  • 如何确保只匹配包含“ 2019”的s2
  • 如何忽略大写/小写字母?

1 个答案:

答案 0 :(得分:1)

您只需将2019.*添加到正则表达式中即可匹配包含Arithm的字符串(通过(?i)不区分大小写) 在字符串中的某个位置后接2019。像这样:(?i)^.*?Arithm.*2019.*$

我知道它不是javascript,但是很方便地看到一个从regex101复制的工作示例:

const regex = /^.*?Arithm.*2019.*$/gmi;
const str = `Arithmetic Return 2018 (%)
Arithmetic Return 2019 (%)`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

Python:

import re

s1 = 'Arithmetic Return 2018 (%)'
s2 = 'Arithmetic Return 2019 (%)'

p = re.compile(r'(?i)^.*?Arithm.*2019.*$')
w = [re.findall(p, a) for a in [s1, s2]]
print(w)