Reputation: 5822
So, VB6/VB.NET has a Like
keyword, which is kind of like a Regex.
I know what this is doing but I am not an expert in Regex and was hoping someone could kindly help (AND I want to use Regex and not string specific stuff like IndexOf/get the last char):
VB code:
If (someDataStr Like "[*]??????????????8") Then
...
end if
So I am focusing on this:
"[*]??????????????8"
what would this be in terms of a Regex expression?
Upvotes: 3
Views: 1067
Reputation: 2593
Building on Martin Büttner's answer, this is what I did to convert the VB Like
operator into a C# Regex
. As the Like
operator in Visual Studio 2013 supports some additional Regular Expression like features, there is a bit of extra work to convert the pattern.
// 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);
Warning: This code is has not been tested!
Upvotes: 0
Reputation: 44259
Based on Damien_The_Unbeliever's link, I assume that your pattern matches a literal *
, 14 arbitrary characters and then a literal 8
.
Then this would be your regex:
@"^\*.{14}8$"
Note that .
will not generally match line breaks. If you need it to, then set the SingleLline
option.
Match match = Regex.Match(input, @"^\*.{14}8$", RegexOptions.Singleline)
if (match.Success)
{
// string has valid format
}
Upvotes: 9