0

How can I check my text if it contains any of the array content as words not "texting"?

string text = "some text here";
string[] array1 = { "text", "here" };
string[] array2 = { "some", "other" };

I've found this code on SO how can I adapt it?

string regexPattern = string.Format(@"\b{0}\b", Regex.Escape(yourWord));
if (Regex.IsMatch(yourString, regexPattern)) {
    // word found
}

Also is regex the best approach for this work? Or should I use a foreach loop?

2
  • 1
    Do you need the keywords to be searched in both arrays (array1 and array2)? Commented Apr 26, 2013 at 7:08
  • No i dont want both arrays searched at least not at the same time. Commented Apr 26, 2013 at 7:24

4 Answers 4

8

Also is regex the best approach for this work?

I avoid regex until there is no other clean, efficient and readable approach, but that's a matter of taste i think.

Is any of the words in the arrays in the words of a string? You can use Linq:

string[] words = text.Split();
bool arraysContains = array1.Concat(array2).Any(w => words.Contains(w));
Sign up to request clarification or add additional context in comments.

4 Comments

Yes i thought that Linq could do it too somehow but my knowledge on Linq is minimum.. That will do the work i think, thanks a lot.
A small update i didnt want to concat the 2 arrays. So i just used this: bool arraysContains = array1.Any(w => words.Contains(w));
@Incognito: The concat does not create a new collection, it's just like a foreach with the first array and then a foreach with the second array. So if one word in the first is contained in the string it won't check the second array at all. I thought that you wanted to check both arrays.
Yes i want to check both arrays but i want to know which array match.
1

If you are going to check whether text contains any string in an array like array1 you may try this:

text.Split(' ').Intersect(array1).Any()

Comments

0

Try this code:

string text = "some text here";

string[] array1 = { "text", "here" };
string[] array2 = { "some", "other" };

bool array1Contains = array1.Any(text.Contains);
bool array2Contains = array2.Any(text.Contains);

1 Comment

This code doesnt fit my in my case i need word matching. if i change the text to "some1 text...." it will be true.
0

If your words may be adjacent to quotes, commas etc. rather than just spaces, you can be a bit more clever than just using Split():

var words = Regex.Split(text, @"\W+");
bool anyFound = words
    .Intersect(array1.Union(array2), StringComparer.CurrentCultureIgnoreCase)
    .Any();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.