简体   繁体   中英

Regex lookahead in javascript

I need to match a string in which single quote or percentage can occur only once

The occurrence is in this way

Starting letter should not be these two special characters Can appear only one time

Example

Valid Cases
Test'
Te'st
Test%
Te%st

Invalid Cases
%Test
'Test
Test%'
Test%%

I am using this way now

/^[a-z ]*(?:[a-z]'|%)?[ a-z]+$/i.test("Tes%t")

But in this I am not able to match Test% or Test' what am i doing wrong here?

Can some one help

In /^[az ]*(?:[az]'|%)?[ az]+$/i.test("Tes%") it is expected to have [ az] one or more times since it is followed by + . If you replace this with * it seems to work fine. Also it is required to replace the [az ]* with [az ]+ in order to disallow the cases of words starting with one of the two characters eg the invalid case you mentioned %Test .

Example, /^[az ]+(?:[az]'|%)?[ az]*$/i.test("Tes%")

scriptular

Here's another pattern that works: /^[^'%]+['%][^'%]*$/

  • ^ starting from the beginning of the line
  • [^'%]+ match one or more characters that are not a ' or %
  • ['%] followed by one character that's a ' or %
  • [^'%]*$ and allow zero or more characters that are not a ' or % until the end of the line

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