dlp1980
(Daniel Pullen)
August 1, 2017, 1:25am
1
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.
Regards,
Dan
ranjith
(Ranjith)
August 1, 2017, 5:09am
2
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;
break;
}
}
1 Like
aksh1yadav
(AKSHAY YADAV)
August 1, 2017, 6:39am
3
dlp1980:
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?
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)
Regards…!!
Aksh
6 Likes
And String.Join(“|”, yourList) for pattern string generation and its golden.
dlp1980
(Daniel Pullen)
August 1, 2017, 1:13pm
5
Thanks for the help everyone, used the Regex & it’s working perfectly!