简体   繁体   中英

Conditional Regex Problem in C#

I want to match a pattern ASA[az][az][0-9][0-9] and replace them with embedded hyperlinks http://www.stack.com?order=ASA[az][az][0-9][0-9] and display it as ASA[az][az][0-9][0-9]

Eg: ASAsq96 or ASApt66

The following conditions should be met before replacement should occur

1.The pattern should not be replaced if it occurs within any href link

<ahref="samplesample?=ASAsq96\%#');"</a>

2.The pattern should not be replaced if it occurs within any http:// link

http://www.test.com/ASA[a-z][a-z][0-9][0-9]/example

http://www.stack.com/ASA[a-z][a-z][0-9][0-9]

3.But, the pattern should be replaced if it only exists within a specific hyperlink of type

 http://replaceme/ASA[a-z][a-z][0-9][0-9] 

4.All other existing patterns outside should be replaced

The regex here perfectly satisfies conditions 2 and 4 . How can I incorporate conditions 1 and 3 into this regex. I am using HTML body to process the body.

mail.HTMLBody = Regex.Replace(mail.HTMLBody, 
"(?<!http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;
\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?)
(ASA[a-z][a-z][0-9][0-9])(?!</a>)", 
"<a href=\"http://www.stack.com?order=$&\">$&</a>");

Is there a good reason why you're trying to combine a bunch of different conditions into a single regular expression? I'd have a separate expression for each condition. This will make your pattern (and logic) a lot more readable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM