1

I'm very new in this Regex, there's still a lot I don't understand.

  1. I see a lot of @, but I can't find it in MSDN. What's the @ for? eg: Regex regex = new Regex("@{lalala},", RegexOptions.Compiled);

  2. This is what I'm having trouble with. I have this string.

    {BaseClass.InheritClass,Tuple.Create("MachineState",string.Empty)},

What I want to do is get the name of the InheritClass and MachineState, put it into variables.

I tried this:

Regex regex = new Regex(@"\{BaseClass.(?<inheritClassStr>\d+),Tuple.Create\(""(?<machineStateStr>\d+)"",string.Empty\)\},", RegexOptions.Compiled);

I was hoping later in the code I could do something like this:

string inheritClassString = inheritClassStr;
string machineStateString = machineStateStr;

But it doesn't work, and I do not know how to debug this. I don't know what the Regex captures, so it's very hard for me to debug.

Your help would be greatly appreciated.

1 Answer 1

1

What you are after is (as in regular expression):

\{BaseClass.(?<inheritClassStr>.*?),Tuple.Create\("(?<machineStateStr>.*?)",string.Empty\)\}

to clarify:

\d that you used will math only numbers but identifiers in C# tend to contain letters as well.

.* would math any character in greedy manner (so the more the better) so it is not a good choice here

.*? will math any character but in not greedy manner (so as small set as possible)

And there is no magic in C# so your declarations in regex wont get converted to variables but you need to access those like this:

var inheritClassString = regex.Groups["inheritClassStr"].Value;

And the @ on the beginning of string just indicates that c# compiler wont try to interpret special characters that can be put in otherwise not prefixed string such as \t\n\r tab, new line, carriage return.

Sign up to request clarification or add additional context in comments.

2 Comments

I still getting unrecognized escape sequence... I changed my Regex to: Regex regex = new Regex("\{BaseClass.(?<inheritClassStr>.*?),Tuple.Create(\"(?<machineStateStr>.*?)\",string.Empty)\}", RegexOptions.Compiled); Still failing. I have 4 unrecognized escape sequence :( If I never put escape sequence before the quotation mark, the RegEx will fail at the quotation mark...
That is exactly the error that @ is for. Prefix your regex with @ replace \" with "" and your good to go.

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.