Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python match a string with regex

Tags:

python

regex

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 = 'This,is,a,sample,string' 

I want to search based on "sample", this would return true. I am crappy with reg ex, so when I looked at the python docs, I saw something like

import re re.match(r'sample', line) 

But I don't know why there was an 'r' before the text to be matched. Can someone help me with the regular expression?

like image 423
Zack Avatar asked Oct 10 '13 15:10

Zack


People also ask

How do you match a string in Python?

Use the string method startswith() for forward matching, i.e., whether a string starts with the specified string. You can also specify a tuple of strings. True is returned if the string starts with one of the elements of the tuple, and False is returned if the string does not start with any of them.

How do I check a string in regex?

Use the test() method to check if a regular expression matches an entire string, e.g. /^hello$/. test(str) . The caret ^ and dollar sign $ match the beginning and end of the string. The test method returns true if the regex matches the entire string, and false otherwise.


1 Answers

Are you sure you need a regex? It seems that you only need to know if a word is present in a string, so you can do:

>>> line = 'This,is,a,sample,string' >>> "sample" in line  True 
like image 148
jabaldonedo Avatar answered Sep 19 '22 09:09

jabaldonedo