【问题标题】:Regex to find by ignoring certain words通过忽略某些单词来查找的正则表达式
【发布时间】:2015-03-22 12:00:37
【问题描述】:

我对正则表达式非常陌生。我想通过忽略“in”、“of”、“the”等常用词以及逗号、反斜杠等特殊字符来搜索字符串中的多个词。

我的代码

  Dim StringToSearchFrom As String = "Thus, one shifts one's focus in a variety of directions all at the same time"
  Dim PhraseToSearch As String = "focus variety directions"
  Dim found1 As Match = Regex.Match(StringToSearchFrom, Regex needed)
        If found1.Success Then
            MsgBox(found1.Index)
        Else

第一个正则表达式在尝试查找并返回PhraseToSearch 的第一个单词(焦点)的索引时应忽略完整的单词“in”、“a”和“of”。谢谢

【问题讨论】:

    标签: regex vb.net


    【解决方案1】:

    您可以使用以下正则表达式,您必须动态构建。这是一个概念验证示例,它将在忽略“a”和“in”的字符串中捕获“焦点变化”:

    Public Dim MyRegex As Regex = New Regex( _
          "focus(?:(?:\b(?:in|of|a|the)\b\s*|[\p{P}\p{S}\p{Z}]*)*)variety", _
        RegexOptions.IgnoreCase _
        Or RegexOptions.CultureInvariant _
        Or RegexOptions.Compiled _
        )
    

    解释

    要使字符串的一部分成为可选的,我们仍然应该能够在模式中捕获它。如果您将查询字符串中的所有可选子字符串替换为(?:(?:\b(?:in|of|a|the)\b\s*|[\p{P}\p{S}\p{Z}]*)*),您将能够匹配单词列表(?:in|of|a|the)(使用您的单词列表更新)、标点符号\p{P}、符号\p{S}、空格@ 中的任何单词987654326@.

      Dim StringToSearchFrom As String = "Thus, one shifts one's focus in a variety of directions all at the same time"
      Dim PhraseToSearch As String = "focus variety directions"
      Dim optional_pattern As String = "(?:(?:\b(?:in|of|a|the)\b\s*|[\p{P}\p{S}\p{Z}]*)*)" 
      Dim rgx_Optional As New Regex(optional_pattern)
      PhraseToSearch = rgx_Optional.Replace(PhraseToSearch, optional_pattern)
      Dim rgx_Search As New Regex(PhraseToSearch)
      ' And then apply our regex
      Dim found1 As Match = rgx_Search.Match(StringToSearchFrom)
        If found1.Success Then
            MsgBox(found1.Index)
        Else
    

    【讨论】:

    • 非常感谢,但我在 Regex.Match(StringToSearchFrom, rgx_Search)
    • 是的,我只是复制了你的代码,没有检查。我把它换成了Dim found1 As Match = rgx_Search.Match(StringToSearchFrom)
    猜你喜欢
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多