VB .net 2010 - 在引用中获取字符串的子串

时间:2018-06-11 12:18:38

标签: string vb.net substring

我有一个包含一些行的文件。我设法找到循环中的所有行。我需要的行看起来像这样:(PS:我瘦了,可以使用正则表达式来做这个......)

if "%testfile%"=="abcd" (

此文件包含更多此行,但abcd更改为任何内容。也可能有不同的空白,如

if  "%testfile%" =="abcd" ( 

我想要

abcd

在我的Loop中的变量中,我可以进一步使用它。

以下部分是这样做的:(lineArray.Item(x)包含整行)

            For x = 0 To lineArray.Count - 1
              If lineArray.Item(x).Contains("%testfile%") Then
                MsgBox(lineArray.Item(x)) 'here should it be done.
              End If
            Next

1 个答案:

答案 0 :(得分:2)

你是绝对正确的,这可以通过正则表达式来完成。我建议这种模式:

(?<=if\s+"%testfile%"\s*==\s*)".*?"(?=\s+\()

Online Demo

<强>解释

  • (?<=if\s+"%testfile%"\s*==\s*)使用额外的+ / optiona *空白\s
  • 查看相关问题。
  • ".*?" layz匹配目标字符串
  • (?=\s+\()看起来像后锚

Code Sample

Imports System
Imports System.Text.RegularExpressions

Public Class Example
    Public Shared Sub Main()
        Dim pattern As String = "(?<=if\s+""%testfile%""\s*==\s*)"".*""(?=\s+\()"
        Dim input As String = "if  ""%testfile%"" ==""abcd"" ( "
        Dim options As RegexOptions = RegexOptions.Multiline

        For Each m As Match In Regex.Matches(input, pattern, options)
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index)
        Next
    End Sub
End Class