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

Regular expression to match words exactly with boundaries

WBOY
Release: 2024-02-12 13:10:09
forward
1117 people have browsed it

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)
Copy after login

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:

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])
    }
}
Copy after login

Output:

'co.'
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template