Contains String with Multi Keywords

Hi all,

I need to search for several keywords in a larger string - at least one keyword found would return True (doesn’t need to find all keywords).

I can use…

Bool = LongString.Contains(“Cat”) OR LongString.Contains(“Dog”) OR LongString.Contains(“Mouse”) OR LongString.Contains(“Snake”)

…but would like to know if there is more efficient/compact code to achieve the same thing?

Thanks in advance.


Hi @dlp1980

Try to store all the keywords in an String array variable and then search for contains in the input string for all keywords in an array.

foreach (string item in Keyword_Array)
if (string_input.Contains(item))
Bool = True;

1 Like

Hey @dlp1980

what about Regex?

you can try this:

String str_data = "This string contains a cat and a Dog keyword. Sometimes snake word also we can include."
bool result = Regex.IsMatch(str_data,"(?i)cat|dog|snake(?-i)") // (?i) within the pattern begins case-insensitive matching, (?-i) ends it

Note - If you don’t want case insensitive search then remove (?i) and (?-i) from the Regex pattern)



And String.Join(“|”, yourList) for pattern string generation and its golden.

Thanks for the help everyone, used the Regex & it’s working perfectly! :slight_smile: