Home > database >  How to check if input string value contains x elements on the right and x elements on left
How to check if input string value contains x elements on the right and x elements on left

Time:02-21

Hello i am trying to make a catch exception for input string for example

if user enters

123test456

the program to say

The first 3 characters must be letter

so it should accept

wowTest456

CodePudding user response:

You can use Take(), with .All() including letter condition,

var validString = inputString
      .Take(3)
      .All(x => Char.IsLetter(x));

You can solve it using Regex too. Credit to @JohnathanBarclay.

bool isInvalidString = Regex.IsMatch(inputString, @"^\d{3}");

Explanation:

  • ^ : Matches the beginning of the string
  • \d: Matches the digit characters
  • {3} : Matches 3 tokens.

To make it positive regex just check \w instead of d

bool validString = Regex.IsMatch(inputString, @"^\w{3}");

Try Online

  •  Tags:  
  • c#
  • Related