Reputation: 621
I am trying to find words in a large text file. The MatchString
method doesn't inherently look for exact word match, rather it looks for the pattern as it should.
How does one check for exact word match using regexp package in Golang? I have tried some regex'es i found on SO, but it didn't work.
Upvotes: 6
Views: 14998
Reputation: 369
If you want to just exactly search for word
string in a large file. You should be using line anchors (https://www.regular-expressions.info/anchors.html)
You must use:
regexp.MatchString("(?sm)^word$", test)
The (?sm)
flags enables the following:
s
as single-line (dotall)m
for multi-line parsingE.g. With the following list
word-
myword
thiswordis
word2
aloja
_word_
.word
word
The pattern regexp.MatchString("(?sm)^word$", test)
will only match the last word
line.
If you use \b
word boudary, you will match the first word-
making this an inexact match.
Upvotes: 2
Reputation: 46442
Use the zero-length word boundry sequence \b
: https://play.golang.org/p/-f0KEKb2EbF
regexp.MatchString("\\bword\\b", test)
Upvotes: 5