Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a regular expression to reject strings containing a period

Tags:

regex

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, but this.isacat should be rejected.

like image 778
guillaumepotier Avatar asked Sep 12 '11 14:09

guillaumepotier


People also ask

How do you use regular expressions for periods?

Any character (except for the newline character) will be matched by a period in a regular expression; when you literally want a period in a regular expression you need to precede it with a backslash. Many times you'll need to express the idea of the beginning or end of a line or word in a regular expression.

What is ?! In regex?

Definition and Usage. The ?! n quantifier matches any string that is not followed by a specific string n.

Is period a special character in regex?

In the regex flavors discussed in this tutorial, there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), the ...

How do you write a negation in regex?

Similarly, the negation variant of the character class is defined as "[^ ]" (with ^ within the square braces), it matches a single character which is not in the specified or set of possible characters. For example the regular expression [^abc] matches a single character except a or, b or, c.


2 Answers

You can use this regex: ^[^.]*$

  1. ^ - beginning of string
  2. [^.]* - any character except ., any number of repetitions
  3. $ - end of string
like image 111
Kirill Polishchuk Avatar answered Oct 12 '22 07:10

Kirill Polishchuk


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)

like image 23
Platinum Azure Avatar answered Oct 12 '22 07:10

Platinum Azure