简体   繁体   中英

How to search for specific word in a single line

I need to search for a particular word in a log file For example, 255 1237 92 D++

I want to scan through each line whether the word "D++" is present. I have tried the approach below but failed.

if re.search(r"D\+\+", Line) is not None:
     print ("Success") 

Thanks

use 'in' keyword

if 'your_str' in line:
   print('Yeah')

Example:

>>> s = 'this has D++ string'
>>> if 'D++' in s:
...    print("OK")
...
OK
>>>

Why not with in ?

if 'D++' in Line:
    print ("Success") 

You can use strings.find

'255 1237 92 D++'.find('D++') > -1    
Out[329]: True

In [330]: '255 1237 92 D++'.find('sdf') > -1                                                                                                                                                               
Out[330]: False

I don't see any mistake in your solution. You can simplify your code:

if re.search(r'D\+{2}', '255 1237 92 D++'):
    print('Success')
# Success

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM