简体   繁体   English

如何使用RegEx匹配C#中的字符串列表?

[英]How can use RegEx to match a list of strings in C#?

I need to find all the regex matches from a list of strings. 我需要从字符串列表中找到所有正则表达式匹配项。 For example, I need to be able to take the string "This foo is a foobar" and match any instances of either "foo" or "bar". 例如,我需要能够获取字符串“This foo is foobar”并匹配“foo”或“bar”的任何实例。 What would the correct pattern be for this? 这个正确的模式是什么? Also, what input sanitation would I need to do to prevent the inputted text from breaking the pattern? 另外,我需要做什么输入卫生来防止输入的文本破坏模式?

I'm a little unsure of what your actual question is. 我有点不确定你的实际问题是什么。 To match "foo" or "bar", you'd simply want "foo|bar" for your pattern. 要匹配“foo”或“bar”,你只需要"foo|bar"作为你的模式。 If you want to do this to a list of strings, you'd likely want to check each string individually—you could join the strings first and check that , but I'm not sure this would be of much use. 如果你想对一个字符串列表这样做,你可能想要单独检查每个字符串 - 你可以先加入字符串并检查 ,但我不确定这会有多大用处。 If you want to get the exact text that matched your pattern, you should surround the pattern in parentheses—such as "([fg]oo|[bt]ar)" , which would match "foo", "goo", "bar", or "tar"—then use the Groups property of the Match object to retrieve these captures, so you can determine exactly which word matched. 如果你想得到与你的模式匹配的确切文本,你应该在括号中包围模式 - 例如"([fg]oo|[bt]ar)" ,这将匹配“foo”,“goo”,“bar “或”tar“ - 然后使用Match对象的Groups属性来检索这些捕获,这样您就可以确切地确定匹配的单词。 Groups[1] is the first captured value (that is, the value in the first set of parentheses in your pattern). Groups[1]是第一个捕获的值(即模式中第一组括号中的值)。 Groups[0] is the entire match. Groups[0]是整场比赛。 You can also name your captures— "(?<word>[fg]oo|[bt]ar)" —and refer to them by name— Groups["word"] . 您也可以命名您的捕获 - "(?<word>[fg]oo|[bt]ar)" - 并按名称 - Groups["word"]引用它们。 I would recommend reading through the documentation on regular expression language elements . 我建议阅读有关正则表达式语言元素的文档。

As for sanitizing the input, there is no input that will "break" the regex. 至于清理输入,没有输入会“破坏”正则表达式。 It might prevent a match, but that's really kinda what regexes are all about, isn't it? 它可能会阻止匹配,但这真的有点像正则表达式,不是吗?

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

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