I have the following regexp:
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:
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:
您可以使用\\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)
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
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.