Hi all I am pretty new to regex world I am trying to match this regex
"\bAsm_vidEmfUpdate_2 (0, ?unknown?)\b"
with this string "Asm_vidEmfUpdate_2 (0, ?unknown?)"
.
I tried to inject '\' before characters '(' , ')' , '?' , ',' to be like this
"\bAsm_vidEmfUpdate_2 \(0\, \?unknown\?\)\b"
but it doesn't work either
But it results in unmatching here is my code
string regexStr = "\bAsm_vidEmfUpdate_2 \(0\, \?unknown\?\)\b";
Regex regex = new Regex(regexStr);
string instr = "Asm_vidEmfUpdate_2 (0, ?unknown?)";
MatchCollection m = regex.Matches(instr);
string str1 = m[0].Groups[0].Value; // ArgumentOutOfRangeException
No, it's matching correctly but you only have a single group (the whole string). So Groups[1]
is invalid - if you ask for Groups[0]
it's fine:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string regexStr = @"Asm_vidEmfUpdate_2 \(0\, \?unknown\?\)";
Regex regex = new Regex(regexStr);
string instr = "Asm_vidEmfUpdate_2 (0, ?unknown?)";
MatchCollection m = regex.Matches(instr);
string str1 = m[0].Groups[0].Value;
Console.WriteLine(str1);
}
}
It's unclear what you're trying to achieve though. Your regex doesn't allow for any flexibility, so you're effectively just asking for string.Contains
. If you're trying to capture the different parts of the string, you might want something like:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string regexStr = @"([A-Za-z_0-9]+) \((\d+), ([^\)]+)\)";
Regex regex = new Regex(regexStr);
string instr = "Asm_vidEmfUpdate_2 (0, ?unknown?)";
Match m = regex.Matches(instr)[0];
foreach (Group group in m.Groups)
{
Console.WriteLine(group.Value);
}
}
}
Output:
Asm_vidEmfUpdate_2 (0, ?unknown?)
Asm_vidEmfUpdate_2
0
?unknown?
(Note that group 0 is still the whole string...)
See more on this question at Stackoverflow