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