简体   繁体   English

regex.replace()中的C#多种模式

[英]C# multiple patterns in regex.replace()

How can i pass multiple patterns to the regex.replace() pattern parameter? 如何将多个模式传递给regex.replace()模式参数?

In PHP you just give up the array containing them. 在PHP中,您只需放弃包含它们的数组。 Is there some kind of same option in C#? C#中是否有某种相同的选项?

I'm looping through some usernames and some of those usernames are surrounded by html tags. 我正在遍历一些用户名,其中一些用户名被html标记包围。 The html tags are not all the same. html标记并不完全相同。 But i do know which ones they are. 但是我知道他们是谁。

So if i can pass multiple patterns to look for in the regex.replace() pattern parameter, would be nice. 因此,如果我可以在regex.replace()模式参数中传递多个模式来寻找,那就太好了。 Or i'll have to make for each html tag a separate pattern and run the regex.replace() function. 或者,我必须为每个html标签制作一个单独的模式,然后运行regex.replace()函数。

Hope i'm clear about what i'm trying to accomplish! 希望我对自己要完成的工作很清楚!

Thanks in advance! 提前致谢!

[EDIT] @Alan Moore, [编辑] @艾伦·摩尔,

Bottom line, removing all html tags out of a string, is what i'm trying to do. 我想做的是,从字符串中删除所有html标签的底线。

[/EDIT] [/编辑]

// I’m assuming you have a regex for each thing you want to replace
List<string> multiplePatterns = [...];

string result = Regex.Replace(input, string.Join("|", multiplePatterns), "");

Use the regexp divider | 使用正则表达式分隔符| , eg: ,例如:

</?html>|</?head>|</?div>

So you have a list of strings, each consisting entirely of a user name optionally enclosed in HTML tags? 因此,您有一个字符串列表,每个字符串完全由一个可选地包含在HTML标记中的用户名组成? It shouldn't matter which tags they are; 它们是哪个标签并不重要; just remove anything that looks like a tag: 只需删除任何看起来像标签的内容即可:

name = Regex.Replace(name, @"</?\w+[^<>]*>", String.Empty);

If performance is important and there's no risk of '<' or '>' in user names, this could work: 如果性能很重要,并且用户名中没有'<'或'>'的风险,则可以这样做:

string RemoveTags(string s)
        {
            int startIndex = s.IndexOf('<');
            int endIndex = s.IndexOf('>');
            return startIndex >= 0 && endIndex >= 0 ? RemoveTags(s.Remove(startIndex, endIndex - startIndex + 1)) : s;
        }

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

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