Regex模式打印组1和组2

zf9nrax1  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(81)

当我尝试在字符串匹配后提取内容,但得到的结果来自Group1时,我是第一次使用正则表达式
正则表达式模式:("Method":)(?s)(.*$)
字符串:I'm a calling a "Method": "Get"
Regex Demo
我希望输出为“Get”

6vl6ewon

6vl6ewon1#

  • 假设 * (?s)是可选的空白字符,那么你的RegEx应该是这样的:
("Method":)\s?(.*)$

$1将匹配"Method":,但这是非常无用的,因为内容是静态的。
$2匹配可选空白字符之后的任何内容。请注意,在这种情况下,捕获组不匹配行尾。
Example

laik7k3q

laik7k3q2#

你可以这样写:

`(?P<firstNamedGroup>"Method"):(?:\s)(?P<secondNamedGroup>.*)$`

(?P“方法”):这是一个名为firstNamedGroup的命名组,它将捕获模式**“Method”**
(?:\s):这是一个非捕获组,将匹配任何空格字符,如空格。这是可选的。你可以这样写
(?P.*):这是一个名为secondNamedGroup的命名组,它将捕获模式**“Get”**
$:这是一个字符串的结尾,在go中不能作为行尾。不知道为什么。

备注:

    • P(?P并不是在所有的正则表达式解释器中都使用。
      我假设你正在使用go语言查看regex 101链接的配置。顺便说一下,这里是更新版本regex101的链接。
      另一个匹配
      new line**/end of line的正则表达式版本也可以这样写:
`(?P<firstNamedGroup>"Method"):(?:\s)(?P<secondNamedGroup>.*)(?:$|\r?\n)`

(?:$?|\r?\n)与字符串“"$"”或结尾匹配的非捕获组|一个回车还是零\r?和换行符\n

此正则表达式版本regex101的链接。
您可以使用下面的脚本示例,其中显示了如何使用命名组go.dev。它是使用ChatGPT生成的,因为我在go中没有使用。

package main

import (
    "fmt"
    "regexp"
)

func main() {
    // Define the input string
    input := `I'm a calling a "Method": "Get"`

    // Define the regular expression pattern with named capturing groups
    pattern := `(?P<firstNamedGroup>"Method"):(?:\s)(?P<secondNamedGroup>"Get")$`

    // Compile the regular expression
    regex := regexp.MustCompile(pattern)

    // Find the first match in the input string
    match := regex.FindStringSubmatch(input)

    // Check if the match was found
    if len(match) > 0 {
        // Create a map to hold the named captures
        captures := make(map[string]string)

        // Extract named captures and store them in the map
        for i, name := range regex.SubexpNames() {
            if i > 0 && i <= len(match) {
                captures[name] = match[i]
            }
        }

        // Print the captured "Method" and "Group"
        fmt.Printf("Method: %s, Group: %s\n", captures["firstNamedGroup"], captures["secondNamedGroup"])
    } else {
        fmt.Println("No match found.")
    }
}

我希望它能回答你的问题。

相关问题