简体   繁体   English

C# 中的条件正则表达式问题

[英]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]我想匹配一个模式 ASA[az][az][0-9][0-9] 并将它们替换为嵌入式超链接 http://www.stack.com?order=ASA[az][az][0 -9][0-9] 并将其显示为 ASA[az][az][0-9][0-9]

Eg: ASAsq96 or ASApt66例如: ASAsq96ASApt66

The following conditions should be met before replacement should occur更换前应满足以下条件

1.The pattern should not be replaced if it occurs within any href link 1.如果出现在任何href链接中,则不应替换该模式

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

2.The pattern should not be replaced if it occurs within any http:// link 2.如果出现在http://链接中,则不应替换该模式

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 3.但是,如果模式只存在于特定类型的超链接中,则应替换该模式

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

4.All other existing patterns outside should be replaced 4.所有其他现有的模式都应该被替换

The regex here perfectly satisfies conditions 2 and 4 .这里的正则表达式完全满足条件 2 和 4 How can I incorporate conditions 1 and 3 into this regex.如何将条件 1 和 3 合并到此正则表达式中。 I am using HTML body to process the body.我正在使用 HTML 主体来处理主体。

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.这将使您的模式(和逻辑)更具可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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