How to check and extract string via RegEx?
I am trying to check if a string ends in "@something" and extract "something" from it if it does. For example, I am trying to do something like this:
string temp = "//something//img/@src"
if (temp ends with @xxx)
{
string开发者_开发知识库 extracted = (get "src");
...
}
else
{
...
}
How can I accomplish this?
From your comments on my other answer, it appears what you need is something like this:
string temp = "//something//img/@src";
var match = Regex.Match(tmp, @"/@([\w]+)$", RegexOptions.RightToLeft);
if (match.Success)
{
string extracted = match.Groups[1].Value;
...
}
else
{
...
}
Don’t use a regular expression for this, it’s not worth it.
string temp = "//something//img/@src"
int pos = temp.LastIndexOf('@');
if (pos != -1)
{
string extracted = temp.Substring(pos+1);
...
}
else
{
...
}
Try the following
var match = Regex.Match(tmp, @".*@(.*)$");
if ( match.Success ) {
var extracted = match.Groups[1].Value;
...
The trick here is the ()
in the regex. This groups the final matching into an unnamed group. This match can then be accessed via the Groups
member on the Match variable by index. It's the first grouping so the index is 1
精彩评论