2013-03-07 52 views
2

我有一个文件中包含的内容:捕获某个子字符串的最佳方法?

garbage 
garbage 
printfile ps = "Elopak Zufriedenheit After Sales.ps"; 
garbage 
garbage 

我想捕捉""(双引号)之间的部分 - 但该部分的值更改不断。我写了一个正则表达式找到printfile ps - 但是从那里出发最好的方法是什么?

新代码:

Dim PFileRegex As New Regex("printfile ps *\t*= *\t*""[\w\s]*.ps\s*""") 
Dim PFilematch As Match = PFileRegex.Match(parttext) 

        If PFilematch.Success = True Then 
         Dim Quote As Char = """"c 
         Dim FirstQuote = PFilematch.Value.IndexOf(Quote) 
         Dim LastQuote = PFilematch.Value.LastIndexOf(Quote) 

         Dim PSFile = PFilematch.Value.Substring(FirstQuote + 1, (LastQuote - FirstQuote) - 1) 
         Debug.Print(PSFile) 
        Else 
         'error handlung 
        End If 

回答

1

下面介绍如何使用Regex类来做到这一点:

Dim PFileRegex As New Regex("^printfile ps\s*=\s*""(?<data>.*\.ps\s*)"";.*$", RegexOptions.Multiline) 
Dim PFilematch As Match = PFileRegex.Match(parttext) 
If PFilematch.Success Then 
    Debug.Print(PFilematch.Result("${data}")) 
End If 
+1

ahh谢谢,这真的很整洁! – 2013-03-07 13:38:37

2

你真的需要为这个正则表达式? String.Substring更高效。

Dim quote As Char = """"c 
Dim first = printfilePs.IndexOf(quote) 
Dim last = printfilePs.LastIndexOf(quote) 
Dim partBetweenQuotes = "" 
If first <> -1 AndAlso last > first Then 
    Dim start = first + 1 
    Dim length = printfilePs.Length - start - (printfilePs.Length - last) 
    partBetweenQuotes = printfilePs.Substring(start, length) 
End If 

DEMO

+0

围绕这件作品有很多文字 - 特别是有很多引号(“)。第一个和最后一个报价可能不在预期的地方。 此外,还有其他的键值对我必须解析 - 所以我认为正则表达式是最通用的方法。 我基本上是解析手写的语法文件 - 并且语法文件的顺序在每个时间点可能会有所不同 – 2013-03-07 13:15:07

+1

我已经结合了我们的两个想法,请参阅我的编辑的详细信息 – 2013-03-07 13:24:28

1

如果你只是想后得到的数值 “prinfile PS =”:

printfile ps *= *"([^"]+)"; 

如果你想获得的所有键值夫妇:

^([^= ]+) *= *"([^"]+)";$ 
+0

这对我不起作用 - 我已经使用了下面的代码: Dim PFileRegex As New Regex(“printfile ps * = *”“([^”“] +)”“;”) – 2013-03-07 13:11:54

相关问题