2

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?

3 Answers 3

1

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
{
   ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

4 Comments

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"
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"
Maybe we can use temp.EndsWith somehow?
@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.)
0

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

2 Comments

Your parameters for Regex.Match are inverted.
Simpler regex and probably more efficient for long input strings: Regex.Match(tmp, @"@(.*?)$", RegexOptions.RightToLeft)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.