-1

I am trying to see if my string starts with a string in an array of strings I've created. Here is my code:

string x = "Table a";
string y = "a table";
string[] arr = new string["table", "chair", "plate"]
if (arr.Contains(x.ToLower())){
    // this should be true
 }
if (arr.Contains(y.ToLower())){
    // this should be false
 }

How can I make it so my if statement comes up true? Id like to just match the beginning of string x to the contents of the array while ignoring the case and the following characters. I thought I needed regex to do this but I could be mistaken. I'm a bit of a newbie with regex.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Brian Upward
  • 59
  • 1
  • 8
  • 1
    unclear what you are asking... please rephrase... additionally. what does the `if(...)` has to do with anything here? what is arr? x is a string? a regex? a what ? – Tomer W Dec 22 '17 at 18:36
  • 3
    I don't see what regex has to do with this question. –  Dec 22 '17 at 18:38
  • 1
    It's still not clear where regular expressions come in... it sounds like you want `StartsWith` (in conjunction with `Any`) – Jon Skeet Dec 22 '17 at 18:55
  • Please, change places what you search with where you search. – JohnyL Dec 22 '17 at 18:57

6 Answers6

2

It seems you want to check if your string contains an element from your list, so this should be what you are looking for:

if (arr.Any(c => x.ToLower().Contains(c)))

Or simpler:

if (arr.Any(x.ToLower().Contains))

Or based on your comments you may use this:

if (arr.Any(x.ToLower().Split(' ')[0].Contains))
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • This doesn't work because it doesn't ignore preceding characters. "a table" should not match "table", however "table a" should be a match. – Brian Upward Dec 22 '17 at 18:59
  • @BrianUpward Use `Split` in this case `if (arr.Any(c => x.ToLower().Split(' ')[0].Contains(c)))` – Salah Akbari Dec 22 '17 at 19:01
  • This is not how you do case insensitive `Contains` - https://stackoverflow.com/questions/444798/case-insensitive-containsstring – Alexei Levenkov Dec 22 '17 at 19:08
0

Because you said you want regex...
you can set a regex to var regex = new Regex("(table|plate|fork)");
and check for if(regex.IsMatch(myString)) { ... }

but it for the issue at hand, you dont have to use Regex, as you are searching for an exact substring... you can use
(as @S.Akbari mentioned : if (arr.Any(c => x.ToLower().Contains(c))) { ... }

Tomer W
  • 3,395
  • 2
  • 29
  • 44
0

Enumerable.Contains matches exact values (and there is no build in compare that checks for "starts with"), you need Any that takes predicate that takes each array element as parameter and perform the check. So first step is you want "contains" to be other way around - given string to contain element from array like:

   var myString = "some string"
   if (arr.Any(arrayItem => myString.Contains(arrayItem)))...

Now you actually asking for "string starts with given word" and not just contains - so you obviously need StartsWith (which conveniently allows to specify case sensitivity unlike Contains - Case insensitive 'Contains(string)'):

      if (arr.Any(arrayItem => myString.StartsWith(
               arrayItem, StringComparison.CurrentCultureIgnoreCase))) ...

Note that this code will accept "tableAAA bob" - if you really need to break on word boundary regular expression may be better choice. Building regular expressions dynamically is trivial as long as you properly escape all the values.

Regex should be

  • beginning of string - ^
  • properly escaped word you are searching for - Escape Special Character in Regex
  • word break - \b

      if (arr.Any(arrayItem => Regex.Match(myString,
            String.Format(@"^{0}\b", Regex.Escape(arrayItem)), 
            RegexOptions.IgnoreCase)) ...
    
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
0

you can do something like below using TypeScript. Instead of Starts with you can also use contains or equals etc..

  public namesList: Array<string> = ['name1','name2','name3','name4','name5'];

// SomeString = 'name1, Hello there';
      private isNamePresent(SomeString : string):boolean{
        if (this.namesList.find(name => SomeString.startsWith(name)))
          return true;
        return false;
      }
Afsar Ali
  • 555
  • 6
  • 17
-1

I think I understand what you are trying to say here, although there are still some ambiguity. Are you trying to see if 1 word in your String (which is a sentence) exists in your array?

@Amy is correct, this might not have to do with Regex at all.

I think this segment of code will do what you want in Java (which can easily be translated to C#):

Java:

x = x.ToLower();
string[] words = x.Split("\\s+");
foreach(string word in words){
    foreach(string element in arr){
        if(element.Equals(word)){
            return true;
        }
    }
} 
return false;

You can also use a Set to store the elements in your array, which can make look up more efficient.

Java:

x = x.ToLower();
string[] words = x.Split("\\s+");
HashSet<string> set = new HashSet<string>(arr);
for(string word : words){
    if(set.contains(word)){
        return true;
    }
} 
return false;

Edit: (12/22, 11:05am)

I rewrote my solution in C#, thanks to reminders by @Amy and @JohnyL. Since the author only wants to match the first word of the string, this edited code should work :)

C#:

    static bool contains(){
        x = x.ToLower();
        string[] words = x.Split(" ");
        var set = new HashSet<string>(arr);
        if(set.Contains(words[0])){
            return true;
        }
        return false;
    }
Ninja
  • 1,012
  • 3
  • 14
  • 29
  • I've edited my question. I basically want to ignore the end of x and just match the beginning of any string in my array. – Brian Upward Dec 22 '17 at 18:50
  • What is `String word : words`? Is it C#? – JohnyL Dec 22 '17 at 18:51
  • 1
    @BrianUpward This solution will match any words in x with any element in the array. It will work in your use case. – Ninja Dec 22 '17 at 18:51
  • 1
    @JohnyL This is Java Syntax. In C#, it is: `foreach(String word in words)` – Ninja Dec 22 '17 at 18:53
  • @Ninja This is good, but OP requires C# - not Java. Do you see tags? – JohnyL Dec 22 '17 at 18:53
  • @Ninja I only want it to match if the beginning of the string is table. If my string says "this table is" I don't want that to be a match. Will that still work? – Brian Upward Dec 22 '17 at 18:55
  • @Amy, Thanks for the advice. I would be happy to edit my answer. – Ninja Dec 22 '17 at 18:57
  • 1
    @JohnyL man you guys are brutal, I just wrote this Java code to give the author good insight to the question, the response can be easily translated from Java to C# as mentioned in my response. – Ninja Dec 22 '17 at 19:02
-1

Sorry my question was so vague but here is the solution thanks to some help from a few people that answered.

var regex = new Regex("^(table|chair|plate) *.*");
if (regex.IsMatch(x.ToLower())){}
Brian Upward
  • 59
  • 1
  • 8
  • 1
    this solution you selected hardcodes the values you search for and doesn't use any contents of your arr. The question you asked was completely irrelevant to your solution and very misleading. – simonzhu Dec 22 '17 at 19:31
  • This answer does not correctly distinguish between `table a` and `tablet` (based on the question `tablet` should not be matched). – Alexei Levenkov Dec 22 '17 at 19:45
  • Instead of just saying I'm wrong it'd be nice to help me with the answer. – Brian Upward Dec 22 '17 at 20:40