zjhsdtc
zjhsdtc

Reputation: 13

Questions on Python regex

The regex looks like this:

r"""\s*(,@|[('`,)]|"(?:[\\].|[^\\"])*"|;.*|[^\s('"`,;)]*)(.*)"""

My questions:

  1. Are [('`,)] and ['`,] different? And why should use [('`,)] instead of ['`,]?
  2. I don't understand this part of the regex: "(?:[\\].|[^\\"])*". It seems to match a string but I don't know why I should use a group or how this part of the regex works.

Upvotes: 0

Views: 77

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124968

  1. [('`,)] and ['`,] are two different character sets. The first one includes the ( and ) characters in what can be matched. They parentheses don't group anything, they are matched literally:

    >>> import re
    >>> re.findall(r"[('`,)]", '()')
    ['(', ')']
    >>> re.findall(r"['`,]", '()')
    []
    
  2. (?:...) creates a non-capturing group; it lets you group a pattern without producing a group in the output. It just means that one of \., ., or anything not using \ or " can match.

Upvotes: 3

Related Questions