开发者

Write a regular expression to reject strings containing a period

开发者 https://www.devze.com 2023-04-04 02:22 出处:网络
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

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: ^[^.]*$

  1. ^ - beginning of string
  2. [^.]* - any character except ., any number of repetitions
  3. $ - 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)".

0

精彩评论

暂无评论...
验证码 换一张
取 消