Regex: optional group

I want to split the line as follows:

abc//def//ghi

in the part before and after the first entry //:

a: abc
b: //def//ghi

I use this regex:

(?<a>.*?)(?<b>//.*)

What works so far.

However, sometimes the source line is missing //, and obviously the regular expression does not match. How can I make the second group optional?

An input like this abcshould be mapped to:

a: abc
b: (empty)

I tried (?<a>.*?)(?<b>//.*)?, but it left me with lots of NULL results in Expresso, so I guess this is the wrong idea.

+3
source share
3 answers

^ $ , ( ).

^(?<a>.*?)(?<b>//.*)?$
+7

Stevo3000 (Python):

import re

test_strings = ['abc//def//ghi', 'abc//def', 'abc']

regex = re.compile("(?P<a>.*?)(?P<b>//.*)?$")

for ts in test_strings:
    match = regex.match(ts)
    print 'a:', match.group('a'), 'b:', match.group('b')

a: abc b: //def//ghi
a: abc b: //def
a: abc b: None
0

Why use group matching? Why not just divide by "//", either as a regular expression, or as a simple string?

use strict;

my $str = 'abc//def//ghi';
my $short = 'abc';

print "The first:\n";
my @groups = split(/\/\//, $str, 2);
foreach my $val (@groups) {
print "$val\n";
}

print "The second:\n";
@groups = split(/\/\//, $short, 2);
foreach my $val (@groups) {
print "$val\n";
}

gives

The first:
abc
def//ghi
The second:
abc

[EDIT: fixed return max. 2 groups]

0
source

Source: https://habr.com/ru/post/1716201/


All Articles