Regular expression to match a dot

后端 未结 6 503
无人共我
无人共我 2020-11-22 09:51

Was wondering what the best way is to match \"test.this\" from \"blah blah blah test.this@gmail.com blah blah\" is? Using Python.

I\'ve tri

6条回答
  •  Happy的楠姐
    2020-11-22 10:41

    In your regex you need to escape the dot "\." or use it inside a character class "[.]", as it is a meta-character in regex, which matches any character.

    Also, you need \w+ instead of \w to match one or more word characters.


    Now, if you want the test.this content, then split is not what you need. split will split your string around the test.this. For example:

    >>> re.split(r"\b\w+\.\w+@", s)
    ['blah blah blah ', 'gmail.com blah blah']
    

    You can use re.findall:

    >>> re.findall(r'\w+[.]\w+(?=@)', s)   # look ahead
    ['test.this']
    >>> re.findall(r'(\w+[.]\w+)@', s)     # capture group
    ['test.this']
    

提交回复
热议问题