什么是正则表达式,以匹配=,空格后的所有匹配项?

I have /components/component[name=fan/10 index=55]/cpu

I want a regex that givens me fan/10 and 55.

I tried stuff like =(.*)\s, but doesn't work. But I'm guessing it has to be done using capturing groups (the () ) somehow?

You may use

=([^\]\s]+)

See regex demo

Details

  • = - an equals sign
  • ([^\]\s]+) - Capturing group 1: any 1 or more chars other than ] and whitespace.

GO demo:

package main

import (
    "fmt"
    "regexp"
)


func main() {
    s := "/components/component[name=fan/10 index=55]/cpu"
    rx := regexp.MustCompile(`=([^\]\s]+)`)
    matches := rx.FindAllStringSubmatch(s, -1)
    for _, v := range matches {
        fmt.Println(v[1])   
    }
}

Output:

fan/10
55

You may try to use something like this:

s := "/components/component[name=fan/10 index=55]/cpu"
re := regexp.MustCompile(`=([^\s\]]*)`)
matches := re.FindAllStringSubmatch(s, -1)
fmt.Println(matches)

Result will be:

[[=fan/10 fan/10] [=55 55]]