I want to split a string containing square brackets '[]', however, when I call re.split in the re package:
re.split('[]',string)
, it turns out to be:
're.error: unterminated character set at position 0'enter code here
.
CodePudding user response:
[
and ]
are meaningful characters in regular expressions. They allow for the creation of sets of characters to match.
For instance, to match 'a'
, 'b'
, or 'z'
: [abz]
.
To match these characters literally escape them with backslashes. Using a raw string (prefixed with r
) removes the need to escape the backslashes with backslashes.
re.split(r'\[\]',string)