Home >Backend Development >Golang >Regular expression to match words exactly with boundaries

Regular expression to match words exactly with boundaries

WBOY
WBOYforward
2024-02-12 13:10:091145browse

Regular expression to match words exactly with boundaries

php editor Zimo is here to introduce to you a powerful text matching tool - regular expressions. Regular expressions can be used to match words to boundaries exactly, allowing us to find what we need more accurately. Whether in scenarios such as text processing, data extraction, or form validation, regular expressions can play an excellent role, making our work more efficient and accurate. Next, we will have an in-depth understanding of the basic syntax and common techniques of regular expressions to help everyone better master this powerful tool.

Question content

I use golang regular expression to match exact words with boundaries, such as "apple", "co.", I can't simply use \b because the word There can be non-alphanumeric characters at the end, like in the example "Company"

I try something like this:

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 want to get "co." directly, how can I adjust my regex to achieve it.

Thanks in advance

Workaround

You can use findallstringsubmatch to grant you access to the capture group: p>

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.'

ideone demo

The above is the detailed content of Regular expression to match words exactly with boundaries. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete