Python match a string with regex

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

    You do not need regular expressions to check if a substring exists in a string.

    line = 'This,is,a,sample,string'
    result = bool('sample' in line) # returns True
    

    If you want to know if a string contains a pattern then you should use re.search

    line = 'This,is,a,sample,string'
    result = re.search(r'sample', line) # finds 'sample'
    

    This is best used with pattern matching, for example:

    line = 'my name is bob'
    result = re.search(r'my name is (\S+)', line) # finds 'bob'
    

提交回复
热议问题