0

I'm trying to make this regex a string literal, and although i can get it to match in an online evaluator can't quite get it in visual studio. I know its a problem with my escape characters, any help would be appreciated.

string pattern = " ^getelementbyid\("(.*?)\" "

Trying to make this a string literal, valid regex in regex evaluator (regex101.com)

Regex regex = new Regex(pattern);
1
  • 3
    You forgot to escape a quote character " in your string literal as \". Commented Aug 1, 2018 at 18:51

2 Answers 2

1

I believe this is what you're looking for:

string pattern = @"^getelementbyid\(""(.*?)""";

P.S. - it looks like you're parsing JavaScript. Since strings in JavaScript can be contained in either double-quotes or single-quotes, you can make your regex more robust like so:

string pattern = @"^getelementbyid\(['""](.*?)['""]";

That will match getelementbyid("myID" as well as getelementbyid('myID'.

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

2 Comments

Thank you this worked well for me, and having the single and double accomodated was a bonus. cheers.
It will also match getelementbyid('myID" or getelementbyid("myID'. It may be better to use @"^getelementbyid\((['""])(.*?)\\1" to check that the opening and closing string quotes are the same.
0

Not entirely sure what you are trying to match against, but based on what it appears you are trying to do, I think you may have 2 issues.

1) As Joe pointed pointed out, you are missing the escape on the first quote after getelementbyid.

2) You are also missing an escape before your first backslash after getelementbyid.

Since you didn't give us an example of what you are trying to validate, this is all just speculation though.

See if the following will provide you with what you are after:

string pattern = " ^getelementbyid\\(\"(.*?)\" ";

Comments

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.