flutter regex to find two lowercase letters with any number of Uppercase letters, digits and symbols

933

You can use a regex like

(?:[^a-z]*[a-z]){2}

See the regex demo. Details:

  • (?: - start of a non-capturing group:
    • [^a-z]* - zero or more chars other than lowercase ASCII letters
    • [a-z] - a lowercase ASCII letter
  • ){2} - end of the grouping construct, match two repetitions

In Dart, you can use

int n = 2;
RegExp rex = RegExp("(?:[^a-z]*[a-z]){$n}");
print(rex.hasMatch("Food")); // => true
Share:
933
Haritha Madhushanka
Author by

Haritha Madhushanka

Updated on December 29, 2022

Comments

  • Haritha Madhushanka
    Haritha Madhushanka over 1 year

    I am new to regular expressions. I want to write a regex to detect two lowercase letters in a String. The String could contain any number of UpperCase letters, digits and symbols. Just want to make sure that the String contains two lowercase letters for sure using the regex expression.

    I tried using

    RegExp(r'[a-zA-Z]{2}')
    

    But it returns true even when the String contains 1 lowercase and 1 uppercase. I want to check if the String contains at least 2 lowercase letters.

    Could someone help?

    • Wiktor Stribiżew
      Wiktor Stribiżew almost 3 years
      Use [a-z][^a-z]*[a-z]
    • Haritha Madhushanka
      Haritha Madhushanka almost 3 years
      That works! Thanks. Can I achieve the same result using a variable to provide how many number of lowercase letters should be there in the String?
    • Wiktor Stribiżew
      Wiktor Stribiżew almost 3 years
      Do you mean at least two or only two? The one above checks at least two.
    • Haritha Madhushanka
      Haritha Madhushanka almost 3 years
      At least two. Not only two. The answer you provided works perfectly. What I want to achieve is the same result, but instead of checking if the String contains only two lowercase Letters, I want to check if the String contains X number of lowercase letters. Could You please provide the answer, sir?
  • Haritha Madhushanka
    Haritha Madhushanka almost 3 years
    Thank you a million times for the perfect explanation as well.
  • Haritha Madhushanka
    Haritha Madhushanka almost 3 years
    At the time, it showed me that I have to wait 1 minute to accept the answer. I forgot to accept it after that. Sorry. I accepted it :)