How do you do this conditional situation with regular expression?
- Begins with alphanumeric
^[a-z0-9]
- Then followed by this optional dot
\.?
- If there is a dot, then it MUST be followed by 2 to 4 alphabets
[a-z]{2,4}
- It must be ends with an alphabet
[a-z]$
- It has to be a dot and only two dots max.
it's like domain names:
yahoo.co.uk
or yahoo.com
, but you cannot do this yah开发者_如何学编程oo.co.u
or this yahoo.co.
, yes something like that.
You can group the optional dot with the 2-4 characters that must follow it: (\.[a-z]{2,4})
. That said, you will have either none, or up to two of these groups of dot + alphabetic characters (\.[a-z]{2,4}){0,2}
.
The must end with [a-z]
part, you can check with a positive lookbehind (?<=[a-z])
giving this as the full regex:
^[a-z0-9]+(\.[a-z]{2,4}){0,2}(?<=[a-z])$
This will work in Perl and PHP regexes (PCRE), but not in JavaScript, because it does not support lookbehind. In this specific case, you can work around that limitation.
If there is at least one dot, there's already a guarantee that it will end in [a-z]
, because that test is in the group that the dot is a part of. If there is no dot, you need to force a [a-z]
at the end. To do this you can turn the one-or-more quantifier (+
) into a zero-or-more (*
) and force the end to be an [a-z]
when there are no "dot groups". When there are dot groups, you can keep the same pattern, but now with at least one mandatory dot.
^([a-z0-9]*[a-z]|[a-z0-9](+\.[a-z]{2,4}){1,2})$
This checks for a string that begins with [a-z][0-9]
and then contains one or two dots followed by 2/4 alphabets. It works (in Python, at least) for the examples you provided (true for yahoo.co.uk
and yahoo.com
, false for yahoo.co.u
and yahoo.co.
)
^[a-z0-9]+(\.[a-z]{2,4}){1,2}$
Edit - upon re-reading, I think you may want this instead:
^[a-z0-9]*([a-z0-9](\.[a-z]{2,4}){1,2}$|[a-z]$)
This will match strings (in addition to the above) that do not include dots but end with a letter, such as yahoo
, but not yahoo2
.
Try this:
^[a-z0-9](\.[a-z]{2,4}|.*[a-z]$)
^[a-z0-9](?=[^.]*\.[^.]+$|[^.]*\.[^.]\.[^.]+$)(\.(?=[a-z][a-z]){1,2}).*[a-z]$
精彩评论