Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - any alphabet except "e"

I want to make a regular expression for any alphabets except "e" This is what I came up with -

/([a-d]|[f-z])+?/i
  • The above regex doesn't match "e" which is good.
  • It matches for "amrica"
  • But it also match "america" but it shouldn't because of the "e" in america

What am I doing wrong?

like image 727
Adam Avatar asked Jun 27 '17 03:06

Adam


People also ask

What does \+ mean in regex?

Example: The regex "aa\n" tries to match two consecutive "a"s at the end of a line, inclusive the newline character itself. Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol.

What does \b mean in regex?

The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1. 1* means any number of ones.


1 Answers

You may use [a-z] character class, but restrict it with a negative lookahead (?!e), group this pattern with a grouping construct (?:...) and add the anchors around the pattern:

/^(?:(?!e)[a-z])+$/i

See the regex demo.

This technique will work in all regex flavors that support lookaheads. Note in Java and some other languages, you may use character class subtraction, but it is not supported by JS RegExp (nor by Python re). E.g., in Java, you could use s.matches("(?i)[a-z&&[^e]]+").

Pattern details:

  • ^ - start of string
  • (?:(?!e)[a-z])+ - 1 or more characters from a-z and A-Z range BUT e and E
  • $ - end of string anchor
  • i - case insensitive modifier.

JS demo:

var rx = /^(?:(?!e)[a-z])+$/i;
var strs = ['america','e', 'E', 'world','hello','welcome','board','know'];
for (var s of strs) {
  console.log(s, "=>", rx.test(s));
}
like image 55
Wiktor Stribiżew Avatar answered Oct 18 '22 12:10

Wiktor Stribiżew