简体   繁体   中英

regex to match letter+number as a seperate word (javascript)

I have the following regexp:

  • (a|b|c|d|k)\\s?-?\\d{1,2}

https://regex101.com/r/r82AyN/2/

It is more or less correct. It should match: letter a,b,c,d or k with one or two numbers . Examples are:

  • a1
  • k12
  • a-2
  • a1. // should match
  • a1 test // should match

But the problem is that it should match only those items that are as separate word, but not within a word. For instance, it should not match these:

  • abolsa1
  • a1slikti
  • abolsa 124
  • abols a12ab
  • vērtība 428

您可以使用\\b来检测单词边界:

\b(a|b|c|d|k)\s?-?\d{1,2}\b

Use \\b to match word boundaries!

\b(a|b|c|d|k)\s?-?\d{1,2}\b

I basically added \\b at the end and start of your original regex. This means that the start and end must be a word boundary.

You can think of a word boundary as

(?<=\w)(?=\W)|(?<=\W)(?=\w)

Demo

Wrap your regex in \\b , that will mean a word boundary at the beginning and the end.

Also, use a character class instead of the group, it is much more efficient:

\b[abcdk]\s?-?\d{1,2}\b

Try it online here .

Other answers are great here. Thought I'd add mine which is slightly different but uses the word boundary \\b concept too

\\b[abcdk]-?\\d{1,2}\\b

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