检查零或一子串的出现

时间:2019-05-23 17:58:42

标签: python regex

有人可以指出如何检查子模式为零或一次的模式吗?

例如,

Test 1-2 (many): blah blah
Test 1-2: blah blah

应同时检测到两条线。

我尝试过:

sub = 'Test\s+(\d+\s*\-\s*\d+)\s*\((.*?)\)?(\:*)\s*(.*)'

但是它没有按预期工作。

2 个答案:

答案 0 :(得分:2)

您可以使用以下内容匹配出现零次或一次的子模式:

(?:sub_pattern)?

其中 (?:...) 是一个非捕获组。在您的特定示例中,问号(匹配零个或一个子模式)设置为\)?,这仅影响单个前面的右括号')'。您应该将整个可选子模式放入一个非捕获组中,因此:

(?:\(.*?\))?

注意:除非要分别提取捕获值,否则不要使用捕获组 (...)

以下是完整正则表达式模式的测试代码:

import re

# a list of testing strings
x = ['Test 1-2 (many): blah blah', 'Test 1-2: blah blah', 'Test 1: no match']

# regex pattern
sub = r'Test\s+\d+\s*-\s*\d+\s*(?:\(.*?\))?:.+'  

for i in x:
    m = re.match(sub, i)
    if m: print(m.group(0)) 
#Test 1-2 (many): blah blah
#Test 1-2: blah blah

答案 1 :(得分:0)

在这里,我们可以在:后面添加一个可选的子表达式,然后在捕获组中收集我们的值,然后在另一个组中收集我们的数字和破折号,也许类似于:

Test\s+([0-9-]+)(.+)?:\s+(.+)

如果我们想添加更多的边界,我们可以做到。我们的其余工作可以编程。

DEMO

测试

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"Test\s+([0-9-]+)(.+?):\s+(.+)"

test_str = ("Test 1-2 (many): blah blah\n"
    "Test 1-2: blah blah")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

演示

const regex = /Test\s+([0-9-]+)(.+)?:\s+(.+)/gm;
const str = `Test 1-2 (many): blah blah
Test 1-2: blah blah`;
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}`);
    });
}

Kenan Güler的另一种方法

RegExp:^(Test\s+\d+-\d+)\b(?:.*?:\s*)(.*)$

演示:https://repl.it/repls/LovableCaringBrowser

  import re

  base_sub_pattern = ["Test 1-2", "blah blah"]

  string = """\
  Test 1-2 (many): blah blah
  Test 1-2: blah blahGGG
  """

  pattern = re.compile(r"^(Test\s+\d+-\d+)\b(?:.*:\s*)(.*)$", re.MULTILINE)
  matches = pattern.findall(string)

  if matches:
    print("found matches:", matches, "\n")

    for match in matches:
      if set(base_sub_pattern).difference(match):
        print("sub-pattern not exist here", match)