简体   繁体   中英

JS Regex match word starting with character but ignore if it's double

So I have this regular exp :: /(?:^|\W)\£(\w+)(?!\w)/g

This is meant to match words following the character £ . ie; if you type Something £here it will match £here .

However, if you type ££here I don't want it to be matched, however, i'm unsure how to match £ starting but ignore if it's ££ .

Is there guidance on how to achieve this?

You can add £ to \W :

/(?:^|[^\w£])£(\w+)/g

Actually, (?!\w) is redundant here (as after a word char, there is no more word chars) and you can remove it safely.

See the regex demo . Details :

  • (?:^|[^\w£]) - start of string or any single char other than a word and a £ char
  • £ - a literal char
  • (\w+) - Group 1: one or more word chars.

If you also don't want to match $£here

(?<!\S)£(\w+)

Explanation

  • (?<!\S) Assert a whitespace boundary to the left
  • £ Match literally
  • (\w+) Capture 1+ word characters in group 1

See a regex101 demo .


If a lookbehind is not supported:

(?:^|\s)£(\w+)

See another regex101 demo .

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