Reputation: 175
Could anyone please point me how to check a pattern in which a sub-pattern occurs zero or once?
For example,
Test 1-2 (many): blah blah
Test 1-2: blah blah
Both lines should be detected.
I tried with:
sub = 'Test\s+(\d+\s*\-\s*\d+)\s*\((.*?)\)?(\:*)\s*(.*)'
But it doesn't work as expected.
Upvotes: 0
Views: 2144
Reputation: 27743
Here, we can add an optional sub-expression, behind the :
, collect our value after that in a capturing group and collect our numbers and dashes in another one, maybe similar to:
Test\s+([0-9-]+)(.+)?:\s+(.+)
If we wish to add more boundaries, we can do that. The rest of our work can be programmed.
# 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}`);
});
}
RegExp: ^(Test\s+\d+-\d+)\b(?:.*?:\s*)(.*)$
Demo: 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)
Upvotes: 0
Reputation: 13998
You can use the following to match a sub-pattern which occurs zero or once:
(?:sub_pattern)?
where (?:...)
is a non-capturing group. In your particular example, the question mark(to match zero or one sub-pattern) is set to \)?
, this influences only the single preceding closing parenthesis ')'. you should put the whole optional sub-pattern into a non-capturing group, thus:
(?:\(.*?\))?
Note: Do NOT use the capturing groups (...)
unless you want to extract their values separately.
Below is a testing code for a full regex 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
Upvotes: 2