问题
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 froma-z
andA-Z
range BUTe
andE
$
- end of string anchori
- 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:
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.
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.
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