2

より大きな文字列に存在する場合と存在しない場合があるサブ文字列があります。存在する場合は、正規表現で取得したい連絡先情報が含まれている必要があります。

メッセージパラメータが制御できないため、この部分文字列が切り捨てられることがあるため、シナリオごとに対応するために、いくつかの異なる正規表現を作成しました。

私が遭遇している問題は、より複雑な表現が私に死ぬことです。これらの式は、私が試したすべての正規表現テストWebサイトで問題なく実行されました。

これが参照用のコードクリップです。

' Look for contact information using regular expressions.  Data we're looking for is in the format below
' "-- Contact: [name] [email] [phone]"
Dim ContactPattern As String
Dim ContactMatch As Match

If SomeStuff Then
' Only look for the [name] block
ContactPattern = "((?:-- Contact: \[)((\w*|\W*|\s*|\S*)*)\])"
' This match attempt works fine.
ContactMatch = Regex.Match(FullString, ContactPattern, RegexOptions.None)

' Do stuff with the results

ElseIf SomeOtherStuff Then
' Look for [name] and [email]
ContactPattern = "((?:-- Contact: \[)((\w*|\W*|\s*|\S*)*)\] \[((\w*|\W*|\s*|\S*)*)\])"
' This match attempt does not get processed.  I receive the message below in the output window.
'The thread '<No Name>' (0x1f58) has exited with code 0 (0x0).
ContactMatch = Regex.Match(FullString, ContactPattern, RegexOptions.IgnoreCase)

' Do stuff with the results

ElseIf SomeOtherOtherStuff Then
' Look for [name] [email] and [phone]
ContactPattern = "((?:-- Contact: \[)((\w*|\W*|\s*|\S*)*)\] \[((\w*|\W*|\s*|\S*)*)\] \[((\w*|\W*|\s*|\S*)*)\])"
' This match attempt does not get processed.  I receive the message below in the output window.
' "The thread '<No Name>' (0x1f58) has exited with code 0 (0x0)."
ContactMatch = Regex.Match(FullString, ContactPattern, RegexOptions.None)

' Do stuff with the results

End If

残念ながら、Googleは私を失敗させました(または私は失敗しました)。誰か考えがありますか?繰り返しますが、正規表現自体はRegexテストサイトで正常に評価されます。

4

1 に答える 1

5

あなたはおそらく壊滅的なバックトラックに遭遇したことがあります。正規表現には、相互に排他的ではないパターンのネストされた繰り返しが含まれています。特に(\w*|\W*|\s*|\S*)*意味がありません。\w\W組み合わせてすべての文字が含まれています。そうし\sてください\S。また、内側のアスタリスクは何も達成しません。これは、外側の繰り返しでもそれを処理できるためです。

達成したいことが、実際にそこにある任意の(\w*|\W*|\s*|\S*)*文字と一致することである場合は、単にすべてを。に置き換えることができます[\s\S]*。あるいは.*、と組み合わせてRegexOptions.Singleline同じことを行います。

于 2012-11-09T19:22:40.907 に答える