views:

38

answers:

3

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?

A: 

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

JaredPar
@Jared: Your parameters for Regex.Match are inverted.
spender
Simpler regex and probably more efficient for long input strings: `Regex.Match(tmp, @"@(.*?)$", RegexOptions.RightToLeft)`
Timwi
@spender, thanks corrected
JaredPar
+1  A: 

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
{
   ...
}
Timwi
Probably the right answer! ;)
spender
Will this work for something like this: //div[@id='large_image_display']//img[@class='photo']/@src (@ signs can be in the middle, but I only want to check if it is at the end like "/@xxx"
TruMan1
@TruMan1: Of course, why do you think I used `LastIndexOf`?
Timwi
But what if I mean is what I had this: //div[@id='large_image_display']//img[@class='photo'] ... It should not match this case. In other words, I am trying to get the check and extract if the end of the string is like this "/@xxx"
TruMan1
Maybe we can use temp.EndsWith somehow?
TruMan1
@TruMan1: You didn’t specify that in your question. You should be specific about your requirements, otherwise it will be unavoidable that the answers you get do not fulfill your unspecified requirements. (All the regex-based answers you received so far have the same behaviour as my answer.)
Timwi
+1  A: 

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