Let's say i want to catch a string, with following conditions :
h
, i
,
, !
h
h
and i
MUST present together (as hi
) at least 1 time. Therefore, accepted (expected) ones could be:
hi
hi!
hhi !!
h ihi !
Non-acceptable , for example:
ih!
<-- becos: no hi
hi
<-- becos: no hi
(together) !hi
<-- becos: didn't start with h
hi! x
hi! x
<-- becos: external character(s) Here is what i tried so far:
var pattern = /^[h]+[i]+[ !]*/i;
pattern.test("hi"); //true <--- expected (correct)
pattern.test("hiiih !"); //true <--- expected (correct)
pattern.test("ihi"); //false <--- expected (correct)
pattern.test(" hi"); //false <--- expected (correct)
pattern.test("hixx"); //true <--- not expected (wrong)
(Which means (so far) i can do all i need, but cannot do characters restrictions.)
May be my whole REGEX should be corrected into different approach. Please help.
This is the regex:
^(?=h)[hi !]*hi[hi !]*$
^(?=h)
: the begin of the string must be followed by an h
[hi !]*
: only the character class [hi !]
is acepted hi
: at some point there is "hi" [hi !]*$
: continue with the character class [hi !]
until reaching the end var pattern = /^h+i+[hi !]*$/i;
The pattern must start with 1 or more 'h', followed by 1 or more 'i', then can contain 'hi !' in any quantity up to the end of the string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.