Reputation: 13500
I need regex to count strings with length of 5 that contain exactly one number (0-9
) and 4 letters (a-z
).
I succeed to find only letters with ^[a-z]{5}$
but I don't know can I tell it find strings that has exactly one number.
For example:
jlwk6 -> one number
bjkgp
5fm8s
x975t
k88q5
zl796
qm9hb -> one number
h6gtf -> one number
9rm9p
jwzw2 -> one number
Total: 4
Upvotes: 1
Views: 370
Reputation: 185580
With Perl :
$ perl -lne '
$count = () = /\d/g;
$gc += $count if $count == 1;
END{print "Total $gc"}
' file
Total 4
Upvotes: 0
Reputation: 627317
You may use
^(?=.{5}$)[a-z]*\d[a-z]*$
See the regex demo
Details
^
- start of string(?=.{5}$)
- there must be 5 chars (other than line break chars) in the string[a-z]*
- 0+ lowercase ASCII letters\d
- a digit[a-z]*
- 0+ lowercase ASCII letters$
- end of string.To extend the solution to N digits, use
^(?=.{5}$)[a-z]*(?:\d[a-z]*){N}$
Here, [a-z]*(?:\d[a-z]*){N}
will match 0+ letters and then N occurrences of a digit followed with 0+ letters.
Upvotes: 2
Reputation: 44476
Use the following Regex:
^[a-z]*\d[a-z]*?(?<=^.{5}$)
Demo at Regex101.
[a-z]*
matches any number of a-z characters before a number \d
.[a-z]*?
matches any number of a-z characters afterward.(?<=^.{5}$)
is a positive lookback - it assures that there are 5 characters exactly between the start and end ^.{5}$
.Upvotes: 0