I have a long string and I have a var inside it
var abc = '123456'
Now I wish to get the 123456 from it.
I have tried a regex but its not working properly
Regex regex = new Regex("(?<abc>+)=(?<var>+)");
Match m = regex.Match(body);
if (m.Success)
{
string key = m.Groups["var"].Value;
}
How can I get the number from the var abc?
Thanks for your help and time
var body = @" fsd fsda f var abc = '123456' fsda fasd f";
Regex regex = new Regex(@"var (?<name>\w*) = '(?<number>\d*)'");
Match m = regex.Match(body);
Console.WriteLine("name: " + m.Groups["name"]);
Console.WriteLine("number: " + m.Groups["number"]);
prints:
name: abc
number: 123456
Your regex is not correct:
(?<abc>+)=(?<var>+)
The +
are quantifiers meaning that the previous characters are repeated at least once (and there are no characters since (?< ... > ... )
is named capture group and is not considered as a character per se.
You perhaps meant:
(?<abc>.+)=(?<var>.+)
And a better regex might be:
(?<abc>[^=]+)=\s*'(?<var>[^']+)'
[^=]+
will match any character except an equal sign.
\\s*
means any number of space characters (will also match tabs, newlines and form feeds though)
[^']+
will match any character except a single quote.
To specifically match the variable abc
, you then put it like this:
(?<abc>abc)\s*=\s*'(?<var>[^']+)'
(I added some more allowances for spaces)
Try this:
var body = @"my word 1, my word 2, my word var abc = '123456' 3, my word x";
Regex regex = new Regex(@"(?<=var \w+ = ')\d+");
Match m = regex.Match(body);
From the example you provided the number can be gotten such as
Console.WriteLine (
Regex.Match("var abc = '123456'", @"(?<var>\d+)").Groups["var"].Value); // 123456
\\d+ means 1 or more numbers (digits).
But I surmise your data doesn't look like your example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.