0

I am using golang regex to match an exact word with boundaries, for example "apple", "co.", I cannot simply use \b, because the word can have non alphanumeric char in the end, like the example "co."

I try something like:

test := `(?i)\b(co.)(?:\s|$)`
re = regexp.MustCompile(test)
matches = re.FindAllString("co. is a secret shortcut ", -1)

but this will give me "co. ", I would like to directly get "co.", how can I adjust my regex to achieve it.

Thanks in advance

Nick
  • 138,499
  • 22
  • 57
  • 95
user2002692
  • 971
  • 2
  • 17
  • 34
  • have you considered having a nested capture so you can grab only that part later? – scso May 27 '23 at 05:17
  • 1
    Does this answer your question? [Regular Expression Word Boundary and Special Characters](https://stackoverflow.com/questions/3241692/regular-expression-word-boundary-and-special-characters) – marco.m May 27 '23 at 12:31
  • @marco.m - Can you explain what you're talking about ? – sln May 27 '23 at 21:58

1 Answers1

2

You could use FindAllStringSubmatch to give you access to the capture group:

package main
import ( "fmt"
        "regexp"
        )

func main(){
    // your code goes here
    test := `(?i)\b(co.)(?:\s|$)`
    re := regexp.MustCompile(test)
    matches := re.FindAllStringSubmatch("co. is a secret shortcut ", -1)
    for _, match := range matches {
        fmt.Printf("'%s'", match[1])
    }
}

Output:

'co.'

Demo on ideone

Nick
  • 138,499
  • 22
  • 57
  • 95