简体   繁体   中英

Javascript REGEX: To allow ONLY specific characters, with a bit of addition conditions?

Let's say i want to catch a string, with following conditions :

  • ONLY these four specific characters are allowed: h , i , , !
  • Any of them can appear multiple times
  • String MUST start with h
  • (Most importantly) 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

See demo

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.

Using a small lookahead and assertion for h at the beginning.

(?=.*hi)^h[hi !]+$    

JSFiddle

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM