Write a regular expression to reject strings containing a period
I'd like to find a regular expression that does not allow strings containing the "." character.
For example, this_is!a-cat
should be accepted开发者_如何学Go, but this.isacat
should be rejected.
You can use this regex: ^[^.]*$
^
- beginning of string[^.]*
- any character except.
, any number of repetitions$
- end of string
Just match on the character and then negate the result:
my $str = 'this.isacat';
my $has_no_comma = !($str =~ !m/\./);
(Note that the above is in Perl, but the concept should work in any language)
^[^\.]*$
This defines a character class which matches all character except the dot. It also specified that the complete string from start to end much consist of character from this class.
/^(?!.*\.).+$/
Should do the trick. Use a negative look-ahead to disqualify anything with a period (remember, it needs to be escaped as a .
in regex means any character).
Alternatively, you can create a class that matches any character but the period:
/^[^.]+$/
The [^
(characters) ]
means "NOT (characters)".
精彩评论