Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group a regular expression in re.split() function?

See two examples how re.split() works:

>>> re.split(',', 'a,b')
['a', 'b']

but

>>> re.split('(,)', 'a,b')
['a', ',', 'b']

Why I get ',' in the list? How to avoid it?

I am asking, because I would like to make a split using an expression similar to 'xy(a|b)cd'.

like image 394
cauchy Avatar asked Jan 28 '12 20:01

cauchy


People also ask

Can you use regex in Split Python?

Regex to Split string with multiple delimiters For example, using the regular expression re. split() method, we can split the string either by the comma or by space. With the regex split() method, you will get more flexibility.

How do you split in regular expressions?

To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.

Can you use regex in Split Javascript?

You do not only have to use literal strings for splitting strings into an array with the split method. You can use regex as breakpoints that match more characters for splitting a string.

What is Groups () in Python?

groups() method. This method returns a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match; it defaults to None. In later versions (from 1.5.


2 Answers

Use a non-capturing group, like:

re.split('(?:,)', 'a,b')
like image 79
Qtax Avatar answered Oct 18 '22 11:10

Qtax


It works that way because it’s documented to work that way:

If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list.

like image 40
Lawrence D'Oliveiro Avatar answered Oct 18 '22 11:10

Lawrence D'Oliveiro