re.compile 中的两种模式

Two patterns in re.compile

我有文本需要在可能有 P/N 或 PN 的地方匹配,但正则表达式必须匹配这两个字符串。

示例代码:

PATTERN = re.compile(r'\(USED ON +P\/N {0,1}([^\)]+)')
text = '(USED ON P/N D511835AAB503)'
match = USED_ON_PN_PATTERN.search(text)
if match:
    print(match.group(1))
else:
    print('else')

输出:

D511835AAB503

但是代码也必须匹配 (USED ON PN D511835AAB503) 并且 match.group(1) 应该 return D511835AAB503.

您只需要在斜杠字符后添加一个?以表示它是可选的。

import re

PATTERN = re.compile(r'\(USED ON +P\/?N {0,1}([^\)]+)')
tests = ['(USED ON P/N D511835AAB503)', '(USED ON PN D511835AAB503)']
for test in tests:
    match = PATTERN.search(test)
    if match:
        print('"{}" matched {}'.format(test, match.group(1)))
    else:
        print('No match in "{}"'.format(test))

输出

"(USED ON P/N D511835AAB503)" matched D511835AAB503
"(USED ON PN D511835AAB503)" matched D511835AAB503