C#某些词后的值正则表达式

我在正则表达式中有一个问题,我有一个看起来像这样的字符串:

  

插槽:0模块:插槽中没有模块

我需要的是一个正则表达式,它可以在插槽和模块之后很好地获取值,插槽始终是一个数字,但是我对模块有问题(这可以是带空格的单词),我尝试过:

 var pattern = "(?<=:)[a-zA-Z0-9]+";
 foreach (string config in backplaneConfig)
 {
     List<string> values = Regex.Matches(config,pattern).Cast<Match>().Select(x => x.Value).ToList();
     modulesInfo.Add(new ModuleIdentyfication { ModuleSlot = Convert.ToInt32(values.First()),ModuleType = values.Last() });
 }

所以插槽部分可以工作,但是模块仅当它是一个没有空格的单词时才起作用,在我的示例中,它只会给我“否”。有没有办法做到这一点

kukuming 回答:C#某些词后的值正则表达式

您可以使用正则表达式在输入字符串中捕获必要的详细信息:

var pattern = @"Slot:(\d+)\s*Module:(.+)";
foreach (string config in backplaneConfig)
{
    var values = Regex.Match(config,pattern);
    if (values.Success)
    {
        modulesInfo.Add(new ModuleIdentyfication { ModuleSlot = Convert.ToInt32(values.Groups[1].Value),ModuleType = values.Groups[2].Value });
    }
 }

请参见regex demo。第1组是ModuleSlot,第2组是ModuleType

详细信息

  • Slot:-文字
  • (\d+)-捕获第1组:一个或多个数字
  • \s*-超过0个空格
  • Module:-文字
  • (.+)-捕获组2:将字符串的其余部分保留到末尾。
,

最简单的方法是在样式中添加“空格”

Public Sub Test()

    Dim sht1 As Worksheet,sht2 As Worksheet,sht3 As Worksheet
    Dim sht1_LastCell As Range
    Dim sht1_Index As Range,rValue As Range
    Dim rFound As Range
    Dim bMismatch As Boolean
    Dim lRowToCopy As Long

    With ThisWorkbook
        Set sht1 = .Worksheets("Sheet1")
        Set sht2 = .Worksheets("Sheet2")
        Set sht3 = .Worksheets("Sheet3")
    End With

    'Return a reference to the last cell on Sheet1.
    Set sht1_LastCell = LastCell(sht1)

    With sht1
        'Look at each cell in Sheet1 Column A
        For Each sht1_Index In .Range(.Cells(1,1),.Cells(sht1_LastCell.Row,1))

            'Ensure the mismatch flag is set to FALSE.
            bMismatch = False

            'Find a match in Sheet2 Column A
            Set rFound = sht2.Columns(1).Find( _
                What:=sht1_Index,_
                After:=sht2.Columns(1).Cells(1),_
                LookIn:=xlValues,_
                LookAt:=xlWhole,_
                SearchOrder:=xlNext)

            'If value is found then compare.
            If Not rFound Is Nothing Then
                'Check each column,excluding column A:
                'OFFSET by 1 column to column B.
                'RESIZE single cell range to all cells from B to last column.
                For Each rValue In sht1_Index.Offset(,1).Resize(,sht1_LastCell.Column - 1)

                    'To reference the correct cell on Sheet2 use the row number that was found
                    'and the column number from the value being looked at.
                    If rValue <> sht2.Cells(rFound.Row,rValue.Column) Then
                        rValue.Interior.Color = RGB(255,255,0)
                        lRowToCopy = rValue.Row
                        bMismatch = True
                    End If
                Next rValue
            End If

            'Copy the data from Sheet1 to the last row (+1 so it doesn't overwrite the last row) on Sheet3.
            If bMismatch Then
                sht1.Rows(lRowToCopy).Copy Destination:=sht3.Cells(LastCell(sht3).Row + 1,1)
            End If

        Next sht1_Index
    End With

End Sub

'UsedRange can return an incorrect reference in certain circumstances.
'This function will always return a reference to the last cell containing data.
Public Function LastCell(wrkSht As Worksheet) As Range

    Dim lLastCol As Long,lLastRow As Long

    On Error Resume Next
        With wrkSht
            lLastCol = .Cells.Find("*",xlByColumns,xlPrevious).Column
            lLastRow = .Cells.Find("*",xlByRows,xlPrevious).Row
        End With

        If lLastCol = 0 Then lLastCol = 1
        If lLastRow = 0 Then lLastRow = 1

        Set LastCell = wrkSht.Cells(lLastRow,lLastCol)

    On Error GoTo 0

End Function

但是最好的解决方案可能是@WiktorStribiżew的答案

,

另一种选择是匹配1个以上的数字,然后匹配单词边界,或者使用您的字符类(但以[a-zA-Z]开头)匹配重复模式

(?<=:)(?:\d+\b|[a-zA-Z][a-zA-Z0-9]*(?: [a-zA-Z0-9]+)*)
  • (?<=:)在左侧声明:
  • (?:非捕获组
    • \d+\b匹配1个以上的数字,后跟一个单词边界
    • |
    • [a-zA-Z][a-zA-Z0-9]*与a-zA-Z开始比赛
    • (?: [a-zA-Z0-9]+)*(可选)重复一个空格和字符类中列出的内容
  • )在捕获组上关闭

Regex demo

,

请替换为:

 // regular exp.
(\d+)\s*(.+)
,

您不需要使用正则表达式进行这种简单的解析。请尝试以下:

:substitute
本文链接:https://www.f2er.com/3167141.html

大家都在问