3

そのため、VB6/VB.NET にはLike、正規表現のようなキーワードがあります。

私はこれが何をしているのか知っていますが、私は正規表現の専門家ではなく、誰かが親切に助けてくれることを望んでいました (そして、正規表現を使用し、IndexOf/get the last char のような特定のものを文字列化したくありません):

VB コード:

If (someDataStr Like "[*]??????????????8") Then
 ...
end if

だから私はこれに焦点を当てています:

"[*]??????????????8"

これは正規表現で表現するとどうなるでしょうか?

4

2 に答える 2

9

Damien_The_Unbeliever のリンクに基づいて、パターンがliteral *、14 個の任意の文字、およびliteral に一致すると仮定します8

次に、これはあなたの正規表現になります:

@"^\*.{14}8$"

.通常、改行と一致しないことに注意してください。必要な場合は、SingleLlineオプションを設定します。

Match match = Regex.Match(input, @"^\*.{14}8$", RegexOptions.Singleline)

if (match.Success)
{
    // string has valid format
}
于 2012-10-30T15:24:35.697 に答える
0

Martin Büttner の回答に基づいて、これは私が VBLikeオペレーターを C#に変換するために行ったことRegexです。Visual Studio 2013のLikeオペレーターは追加の正規表現のような機能をサポートしているため、パターンを変換するための追加作業が少しあります。

// escape RegEx special characters
var pattern = Regex.Escape(likePattern);
// convert negative character lists into RegEx negative character classes
pattern = Regex.Replace(pattern, @"\\\[!(?<c>[^\]]*)\\\]", @"[^${c}]", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture);
// convert positive character lists into RegEx positive character classes
pattern = Regex.Replace(pattern, @"\\\[(?<c>[^\]]*)\\\]", @"[${c}]", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture);
// convert asterisks into RegEx pattern for zero or more characters
pattern = Regex.Replace(pattern, @"(?<!\[[^\]]*)\\*(?![^\]*\])", @".*", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture);
// convert question marks into RegEx pattern for any single character
pattern = Regex.Replace(pattern, @"(?<!\[[^\]]*)\\?(?![^\]*\])", @".", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture);
// convert hash/number sign into RegEx pattern for any single digit (0 - 9)
pattern = Regex.Replace(pattern, @"(?<!\[[^\]]*)#(?![^\]*\])", @"[0-9]", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture);
// make pattern match whole string with RegEx start and end of string anchors
pattern = @"^" + pattern + @"$";

// perform "like" comparison
return Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);

警告: このコードはテストされていません!

于 2016-04-21T19:09:57.907 に答える