I want to match "3 T1F ROHITE01WMILWWI16" which contains only caps letter and numbers nothing else. The condition is that it ,must be both. It should not return true for all alphabetic and all numeric.
Test cases:
I am using ^[0-9 A-Z]+$ it matches correctly the first and last test case but also returns true for fourth test case i.e 1234.
You can use
^([0-9 A-Z]*[A-Z][0-9 A-Z]*[0-9][0-9 A-Z]*|[0-9 A-Z]*[0-9][0-9 A-Z]*[A-Z][0-9 A-Z]*)$
It matches
^
- start of string
[0-9 A-Z]*
- 0+ allowed characters[A-Z]
- one uppercase ASCII letter (obligatory subpattern)[0-9 A-Z]*
- 0+ allowed characters[0-9]
- a digit[0-9 A-Z]*
- 0+ allowed characters
1A
or A1
strings.$
- end of stringThus, the minimum required string length is 2 characters.
See the regex demo and the IDEONE demo:
s <- c("3 T1F ROHITE01WMILWI16", "3 T1F ROHITE01WMILwI16", "3 T1F ROHITE01WMIL.I16", "1234", "aaaa", "T1F ROHITH01WMILWI16")
grep("^[0-9 A-Z]*[A-Z][0-9 A-Z]*[0-9][0-9 A-Z]*$", s, value=TRUE)
If you need to support strings of any length, use this PCRE regex:
^(?=[^A-Z]*[A-Z])(?=[^0-9]*[0-9])[0-9 A-Z]*$
The (?=[^A-Z]*[A-Z])
lookahead requires at least one uppercase letter and (?=[^0-9]*[0-9])
requires one digit.
See the IDEONE demo:
s <- c("3 T1F ROHITE01WMILWI16", "3 T1F ROHITE01WMILwI16", "3 T1F ROHITE01WMIL.I16", "1234", "aaaa", "T1F ROHITH01WMILWI16")
grep("^(?=[^A-Z]*[A-Z])(?=[^0-9]*[0-9])[0-9 A-Z]*$", s, perl=TRUE, value=TRUE)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With