如何查找正则表达式命名组 [英] how to find Regular expression named groups

查看:32
本文介绍了如何查找正则表达式命名组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这条线的图案是什么

\\input var: x(length),y(height),z(width)

我想知道命名的变量组(比如这个 x,y,z)和命名的特定变量的含义组(比如这个长度,宽度,高度)

I want to know named group of variables( like in this x,y,z) and named group of meaning of particular variable( Like in this length,width,height)

我尝试了此文本行的模式

I tried the pattern for this text line

\\input var: x(length),y(height),z(width)

[\/\/\binput\b\s?\bvar\b:\s](\w+)\((.*?)\)\,?

我只能得到 group(1).value 作为 xgroup(2).value 作为长度

I am only able to get group(1).value as x group(2).value as length

我将如何找到其他值,如 y 、高度、z、宽度

How i will find other values like y , height, z, width

推荐答案

这是一个解决方案,我使用了两种正则表达式,一种用于从原始字符串中获取输入,然后另一种用于获取输入及其含义出结果.

Here's a solution, I've used two regular expressions, one to get the inputs out of the original string, and then another to get your inputs and their meanings out of the result.

Dim textToParse As String = "\\input var: x(length),y(height),z(width)"

' Regex matches the start of the string and zero or more input(meaning) portions
Dim extractInputsSectionRegex As New Regex("\\\\input\s*(?<variable>var):\s*(?<inputs>(\w+\(\w+\),*\s*)*)")
' Regex matches an individual input and meaning and returns the captures in named groups
Dim extractIndividualInputsRegex As New Regex("(?<input>\w+)\((?<meaning>\w+)\)")

' Match the input string to extract inputs and meanings
Dim initialMatch As Match = extractInputsSectionRegex.Match(textToParse)

If initialMatch.Success = True Then

    ' Extract inputs and meanings
    Dim inputsSection As String = initialMatch.Groups("inputs").Value

    ' Match one or more input(meaning) portions
    Dim inputMatches As MatchCollection = extractIndividualInputsRegex.Matches(inputsSection)

    If inputMatches.Count > 0 Then

        ' Loop through each match found
        For Each inputMatch As Match In inputMatches

            ' Extract input and meaning
            Dim input As String = inputMatch.Groups("input").Value
            Dim meaning As String = inputMatch.Groups("meaning").Value

            ' Display
            Console.WriteLine("Input: " & input & ", meaning: " & meaning)

        Next

    End If

End If

使用给定的输入和以下字符串进行测试:

Tested using the given input and the following strings:

\\input var: vol(volume),a(area)
\\input var: x(length), y(height), z(width)

这篇关于如何查找正则表达式命名组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆