0

I'm trying to write some code in C# to extract information out of a string using a regex:

var regex = new Regex("href=/skin/(.*)");
var matches = regex.Matches(line);
foreach (string regfr in matches)
    MessageBox.Show(regfr);

I'm doing something REALLY WRONG, I've done regex before but here it's much more confusing.

I want to turn:

<a href="/skin/result1">

into:

result1

i used this in php on preg_match which is easy to use..

a%20href="/skin/(.*)"

and it worked, this is probably really easy, but I'm extremely confused with the way these object-oriented things work :P

1
  • Where are double quotes? Commented Mar 4, 2015 at 21:23

2 Answers 2

1

In var matches = regex.Matches(line);, matches is a MatchCollection. You cannot declare the items as strings.

Your error message says that a Match object cannot be cast to a String.

You should first cast the MatchCollection to the array or list of something that can be iterated. Like this:

var regex = new Regex(@"href=""/skin/([^""]*)(?="")");
var line = @"<a href=""/skin/result1"">";
var matches = regex.Matches(line);
foreach (var regfr in matches.Cast<Match>().ToList())
    MessageBox.Show(regfr.Groups[1].Value);
Sign up to request clarification or add additional context in comments.

2 Comments

it works,so thank you for that,im not sure what this means:matches.Cast<Match>().ToList()
@timo_pomer: BTW, using this .Cast() allows you to use LINQ on the match collection. It turned out a very handy thing for me.
0

Try :

var regex = new Regex("href=\"/skin/(.+?)\"");
var matches = regex.Matches(line);
foreach (string regfr in matches)
    MessageBox.Show(regfr);

The only issue with your current Regex pattern is that it is missing " after =. So, href=/skin/(.*) must be href="/skin/(.*)

1 Comment

i see you escaped many things.2 questions.1:why .+? and not all matches like i did? 2:im getting this error i.imgur.com/bLpTt1p.png

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.