Python match a string with regex

前端 未结 6 511
天命终不由人
天命终不由人 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:07

    The r makes the string a raw string, which doesn't process escape characters (however, since there are none in the string, it is actually not needed here).

    Also, re.match matches from the beginning of the string. In other words, it looks for an exact match between the string and the pattern. To match stuff that could be anywhere in the string, use re.search. See a demonstration below:

    >>> import re
    >>> line = 'This,is,a,sample,string'
    >>> re.match("sample", line)
    >>> re.search("sample", line)
    <_sre.SRE_Match object at 0x021D32C0>
    >>>
    

提交回复
热议问题