首页 > 解决方案 > Vb.net 不按任何特定顺序搜索字符串

问题描述

所以我遇到了一个问题,我无法完全理解它,希望我能正确解释这一点。

我在 VB.net 工作

我的字符串是

来自杰克逊的国家气象局:匹兹堡 [PA]、根西岛、贝尔蒙特 [OH] 至下午 3:45 CDT 的严重雷暴警告 [风速:60 MPH,冰雹:1.00 IN]

所以这是我的问题,上面列出的县可以在每个给定的警告/观察/咨询中按任何顺序排列,所以 PA 可以列在第一位或最后或中间。

这就是我所需要的,我需要能够将 PA 的县分成一个部分,OH 在另一个部分,WV 到另一个部分等等......

示例:Belmon, Guernsey, Noble [OH] Marshall, Ohio, Wetzel [WV]

请记住,县和州可以从警告变为警告。

我的总体目标是,Marion [OH] 和 Marion [WV] 可能处于同一警告中,我想将 Marion [WV] 排除在外,并将 Marion [OH] 与可能列出的任何其他县一起保留。

Dim string1 As String
string1 = Split(TextBox1.Text, "till")(0)
If InStr(TextBox1.Text, "[PA]") Then
    string1 = Split(string1, "[PA]")(1)
    string1 = Replace(string1, ", ", ",")
    string1 = Replace(string1, ",", "|")
    string1 = Split(string1, "[OH]")(0)
Else
    If InStr(TextBox1.Text, "[WV]") Then
        string1 = Split(string1, "[WV]")(1)
        string1 = Replace(string1, ", ", ",")
        string1 = Replace(string1, ",", "|")
        string1 = Split(string1, "[OH]")(0)
    End If
End If

TextBox2.Text = string1

标签: vb.net

解决方案


看来您需要解析字符串。我建议您阅读“正则表达式”(简而言之RegEx)。这是一种在字符串中查找内容的方法。

例如,RegEx搜索模式\[(PA|OH|CA)\]将为您提供给定源字符串中字符串“[PA]”或“[OH]”或“[CA]”的任何出现。

Imports System.Text.RegularExpressions

Public Module Module1

    Sub Main()
        Dim source As String = "From the National Weather Service in Jackson: Severe Thunderstorm Warning [wind: 60 MPH, hail: 1.00 IN] for Pittsburgh [PA],Guernsey, Belmont [OH] till 3:45 PM CDT"
        Dim searchPattern As String = "\[(PA|OH|CA)\]"
        Dim matches As MatchCollection

        matches = Regex.Matches(source, searchPattern)

        For Each match As Match In matches
            Console.WriteLine(String.Format("{0} at position {1} in source string", match.Value, match.Index))
        Next match

        Console.ReadKey()
    End Sub

End Module

这个简短的控制台程序向您展示了如何RegEx在 VB.NET 中使用。

现在您知道在源字符串中可以找到状态缩写的位置,现在您可以解析源字符串以获取所需的其余信息。

请务必RegEx彻底测试您的搜索模式,因为通常它们捕获的内容比您想象的要多或少。有很多网站可以测试RegEx搜索模式(例如https://regex101.com


推荐阅读