TruMan1
TruMan1

Reputation: 36098

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?

Upvotes: 2

Views: 661

Answers (3)

Timwi
Timwi

Reputation: 66573

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
{
   ...
}

Upvotes: 1

JaredPar
JaredPar

Reputation: 754763

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

Upvotes: 0

Timwi
Timwi

Reputation: 66573

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
{
   ...
}

Upvotes: 1

Related Questions