Regex - any alphabet except “e”

倖福魔咒の 提交于 2021-02-19 02:09:39

问题


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?


回答1:


You need the anchors ^ (beginning of the string) and $ (end of the string); otherwise your pattern can partially match any string as long as it contains an alphabet other than e:

/^[a-df-z]+$/i.test("america")
// false

/^[a-df-z]+$/i.test("amrica")
// true

/^[a-df-z]+$/i.test("e")
// false



回答2:


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));
}



回答3:


You can also add Capital in reg use this:

^[a-df-zA-DF-Z]+$

i.test("America")
// false

i.test("Amrica")
// true

i.test("e")   or  i.test("E") 
// false

Please refer many online website to learn regex creation Step by Step https://regex101.com




回答4:


A couple of alternative answers are:

  1. Use a lookahead:

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

This is first checking that the next character is a letter, and then checks that it's not an e (or E).

This is valid regex syntax in JavaScript, but is less performant than the accepted answer.

  1. Use set intersection:

    /^[[a-z]&&[^e]]+$/i
    

This is matching characters in the set intersection of "a-z" and "not e".

This is not valid syntax in JavaScript. However, it is equally performant as the accepted answer. It's only valid syntax in various other regex "flavours" such as Java, Perl, PHP, Python and Ruby.

  1. Use set subtraction:

    /^[[a-z]--[e]]+$/i
    

This is matching characters in the set subtraction of "a-z" and e.

This is not valid syntax in JavaScript. However, it is equally performant as the accepted answer. It's only valid syntax in various other regex "flavours" such as Python and .Net. (Syntax also varies slightly, e.g. - vs --.)



来源:https://stackoverflow.com/questions/44771741/regex-any-alphabet-except-e

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!