Python match a string with regex

前端 未结 6 512
天命终不由人
天命终不由人 2020-12-17 07:38

I need a python regular expression to check if a word is present in a string. The string is separated by commas, potentially.

So for example,

line =          


        
6条回答
  •  抹茶落季
    2020-12-17 08:17

    r stands for a raw string, so things like \ will be automatically escaped by Python.

    Normally, if you wanted your pattern to include something like a backslash you'd need to escape it with another backslash. raw strings eliminate this problem.

    short explanation

    In your case, it does not matter much but it's a good habit to get into early otherwise something like \b will bite you in the behind if you are not careful (will be interpreted as backspace character instead of word boundary)

    As per re.match vs re.search here's an example that will clarify it for you:

    >>> import re
    >>> testString = 'hello world'
    >>> re.match('hello', testString)
    <_sre.SRE_Match object at 0x015920C8>
    >>> re.search('hello', testString)
    <_sre.SRE_Match object at 0x02405560>
    >>> re.match('world', testString)
    >>> re.search('world', testString)
    <_sre.SRE_Match object at 0x015920C8>
    

    So search will find a match anywhere, match will only start at the beginning

提交回复
热议问题