RegEx that must have at least 3 alpha characters
I'm trying to create a expression to check that a response has at least three lette开发者_运维问答rs. Numbers, spaces and all other characters are valid. What I have below only works if a special character doesn't come first.
(?=(.*[a-zA-Z]){3,})^[a-zA-Z0-9].+$
You can use a much simpler regex: ([a-zA-Z].*?){3}
This matches a letter, optionally followed by other characters, repeated three times.
(?:[a-zA-Z][^a-zA-Z]*){3}
Matches (a letter, followed by any non-letters) 3 times. The (?:)
makes it a little more efficient because the regex engine does not have to capture.
Of course it might be easier to read and understand without the regex. Here's C#/linq example.
if (s.Count(char.IsLetter) >= 3)
{
// is valid.
}
My solution: (.*[a-zA-Z].*){3}
It is pretty similar to @SLaks'; the difference is that my code works if you have alpha characters enclosed in special characters like <script>
.
@ridgerunner has a neat solution, but if the end of the string is an special character it won't match. You can see the example in this image:
None of the answers use the correct definition of a letter.
A letter is not [a-zA-Z]
. Here's the Unicode category of lowercase letters: https://www.compart.com/en/unicode/category/Ll
It includes 2,155 entries, because latin is not the only alphabet in the world. For example, the Ukrainian phrase "Слава Україні!" doesn't pass the [a-zA-Z]+
regex. (https://regex101.com/r/n7PINx/1)
To correctly classify letters, use the unicode letter category with the \p{L}
element: \p{L}{3}
matches at least three letters, therefore the regex (\p{L}.*?){3}
will match any string that has at least three letters. Additionally, you might want to anchor the regex to make sure it's the whole string that gets matched: ^(.*?\p{L}.*?){3}$
(https://regex101.com/r/sQQXtR/1).
Saying \p{L}
is much more robust than [a-zA-Z]
, and also more self-explanatory – it's the letter group, not "these particular range of ASCII".
精彩评论