Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String exact match

Tags:

I have a string in which the word "LOCAL" occurs many times. I used the find() function to search for this word but it returns another word "Locally" as well. How can I match the word "local" exactly?

like image 846
Lalit Chattar Avatar asked Nov 13 '10 17:11

Lalit Chattar


People also ask

What is exact string match?

The Exact String Match comparison is a simple comparison that determines whether or not two String/String Array values match. Use the Exact String Match comparison to find exact matches for 2 values for a String identifier.

How do you match an exact string in Python?

Exact match (equality comparison): == , != As with numbers, the == operator determines if two strings are equal. If they are equal, True is returned; if they are not, False is returned. It is case-sensitive, and the same applies to comparisons by other operators and methods.

What is string regex?

A regular expression (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.


2 Answers

For this kind of thing, regexps are very useful :

import re  print(re.findall('\\blocal\\b', "Hello, locally local test local.")) // ['local', 'local'] 

\b means word boundary, basically. Can be space, punctuation, etc.

Edit for comment :

print(re.sub('\\blocal\\b', '*****', "Hello, LOCAL locally local test local.", flags=re.IGNORECASE)) // Hello, ***** locally ***** test *****. 

You can remove flags=re.IGNORECASE if you don't want to ignore the case, obviously.

like image 50
Vincent Savard Avatar answered Oct 04 '22 04:10

Vincent Savard


Below you can use simple function.

def find_word(text, search):     result = re.findall('\\b'+search+'\\b', text, flags=re.IGNORECASE)    if len(result)>0:       return True    else:       return False 

Using:

text = "Hello, LOCAL locally local test local." search = "local" if find_word(text, search):   print "i Got it..." else:   print ":(" 
like image 44
Guray Celik Avatar answered Oct 04 '22 06:10

Guray Celik