How can I use RegEx to match a list of strings in C #?

I need to find all regex matches from a list of strings. For example, I need to be able to take the string "This foo is foobar" and match any instances of "foo" or "bar". What would be the correct template for this? Also, what kind of input sanitation would I need to do to prevent the typed text from being inserted from the template?

+1


source to share


1 answer


I don't know a bit what your real question is. To match "foo" or "bar" you just need "foo|bar"

to match your template. If you want to do this with a list of strings, you probably want to check each line separately - you can join the strings first and check it out, but I'm not sure if that would be very helpful. If you want to get the exact text that matches your pattern, you must surround the pattern in parentheses, for example "([fg]oo|[bt]ar)"

, which will match "foo", "goo", "bar" or "tar", and then use Groups

an object property Match

to retrieve those captures. so you can pinpoint exactly which word matched.Groups[1]

is the first fixed value (that is, the value in the first set of parentheses in your template).Groups[0]

- the whole match. You can also name your pictures "(?<word>[fg]oo|[bt]ar)"

and refer to them by name Groups["word"]

. I would recommend reading the documentation for the regex language elements .



As far as disinfecting the input, there is no input that breaks the regex. It might get in the way of a match, but it's really kinda curious that all are regular expressions, isn't it?

+4


source







All Articles