如何vb.net拆分字符串

时间:2017-06-17 05:07:54

标签: vb.net

我有一个文件txt文件,我希望在值之后拆分值" accession_number ="在价值"& token"

之前

示例文本文件中的值:

10.0.0.6:80/ImageSuite/Web/Worklist/DICOMViewer.aspx?patient_id=5049885&study_uid=201702060824&accession_number=20170206082802&token

10.0.0.6:80/ImageSuite/Web/Worklist/DICOMViewer.aspx?patient_id=4409276&study_uid=201702060826&accession_number=20170206083002&token

10.0.0.6:80/ImageSuite/Web/Worklist/DICOMViewer.aspx?patient_id=4402764&study_uid=201702060801&accession_number=20170206080416&token

10.0.0.6:80/ImageSuite/Web/Worklist/DICOMViewer.aspx?patient_id=4402537&study_uid=201702060837&accession_number=20170206084025&token

proccess后的示例值:
20170206082802
20170206083002
20170206080416
20170206084025

谢谢

2 个答案:

答案 0 :(得分:1)

您可以通过读取所有行,然后根据您可以执行以下代码的行来执行此操作(假设您要读取的文件位于C:\ test.txt)

dim results = from line in File.ReadAllLines("C:\test.txt") _
              where not String.IsNullOrWhiteSpace(line) _
              from field in line.Split("&") _
              where field.StartsWith("accession_number=") _
              select field.Split("=")(1)
for each result in results
    Console.WriteLine(result)
next

这将用作所有行的输入,然后对于非空的行,它将使用&进行拆分,然后检查该字段是否以accession_number开头,如果是,则按{分割{1}}返回数组中的第二项。

作为额外的解释:

=

同时评估文件中的每一行

from line in File.ReadAllLines("C:\test.txt")

将排除所有空行(或仅存在空格的行)

' input eg: 10.0.0.6:80/ImageSuite/Web/Worklist/DICOMViewer.aspx?patient_id=5049885&study_uid=201702060824&accession_number=20170206082802&token
where not String.IsNullOrWhiteSpace( line )

将使用from field in line.Split("&") 作为分隔符

将每个找到的行拆分为字符串数组
&

将排除所有不以 ' field eg: accession_number=20170206082802 where field.StartsWith("accession_number=")

开头的字段
accession_number=

将返回 select field.Split("=")(1) ' result sample: 20170206082802

之后的所有匹配项

您可以在此dotnetfiddle找到完整示例。它使用稍微不同的方法从流中读取,只是因为在那个环境中,我无法提供虚拟文件,但是,它应该可以做到这一点

答案 1 :(得分:1)

您可以使用File.ReadAllLines()将每一行读入一个字符串数组中,然后对其进行迭代并使用Regex解析信息。

'Declare the Regex.
Dim Parser As New Regex("(?<=accession_number\=)\d+", RegexOptions.IgnoreCase)

'Read the file's lines into an array of strings.
Dim Lines As String() = File.ReadAllLines("C:\test.txt")

'Iterate over the array.
For Each Line As String In Lines
    Dim m As Match = Parser.Match(Line) 'Match the pattern.
    If m.Success = True Then 'Was the match successful?
        Console.WriteLine(m.Value) 'Print the matched value.
    End If
Next

在线测试:http://ideone.com/VU5Iyj

正则表达式模式说明:

(?<=accession_number\=)\d+

(?<=                      => Match must be preceded by...
    accession_number\=    => ..."accession_number=".
)                         => End of preceding capture group.
\d+                       => Match one or more numerical characters.