c_prog_90
c_prog_90

Reputation: 949

Complex Regex problem with hyperlink not matching "?"

I am working in replacing a text with a hyperlink in C#. The problem here is that the link has a question mark

Case 1:No problem

Input: ASAss123

Output:ASAss123

Case 2:Problem here

Input: ASAsq123

Output:ASAsq123">ASAsq123

(Note: First occurrence of ASAss123 is hyperlink and is replaced as http://stack.com/temp/test?order=sam&identifier=<a href= and second occurrence is just plain text)

Preferred Output: ASAsq123

How can I rectify this problem. Code here for your reference:

 mailItem.HTMLBody = Regex.Replace(
     mailItem.HTMLBody,
     "(?<!http://stack.com/temp/test?order=sam&identifier=)ASA[a-z][a-z][0-9][0-9][0-9](?!</a>)",
     "<a href=\"http://stack.com/temp/test?order=sam&identifier=$&\">$&</a>");

The problem here is with the "?" found in the second argument. If I get rid this of "?" in both 2nd and 3rd arguments, this works perfectly fine.

But I cannot get rid of "?", because it is needed for the URL to function. How can I solve this problem?

I tried escape sequence with \? and C sharp says escape sequence unrecognized...

Upvotes: 0

Views: 167

Answers (3)

Ssithra
Ssithra

Reputation: 710

C# doesn't recognize the sequence \? because it is a regex one, not a C# one.

To prevent C# from trying to recognize escape sequences in your string and make C# treat your \? like any other characters, you must prefix your string with @ :

mailItem.HTMLBody = Regex.Replace(
 mailItem.HTMLBody,
 @"(?<!http://stack.com/temp/test?order=sam&identifier=)ASA[a-z][a-z][0-9][0-9][0-9](?!</a>)",
 "<a href=\"http://stack.com/temp/test?order=sam&identifier=$&\">$&</a>");

Upvotes: 2

Petar Ivanov
Petar Ivanov

Reputation: 93050

You need to escape like this:

\\?

You are escaping ? In the regex, but \ needs to also be escaped in the c# string.

Upvotes: 3

agent-j
agent-j

Reputation: 27943

It looks like you need to escape your test? like test\? so it doesn't mean optional t.

Upvotes: 4

Related Questions