Javascript - regex - word boundary (\\b) issue

有些话、适合烂在心里 提交于 2019-11-27 22:53:58

Since Javascript doesn't have the lookbehind feature and since word boundaries work only with members of the \w character class, the only way is to use groups (and capturing groups if you want to make a replacement):

(?m)(^|[^a-zA-ZΆΈ-ώἀ-ῼ\n])([a-zA-ZΆΈ-ώἀ-ῼ]{2})(?![a-zA-ZΆΈ-ώἀ-ῼ])

example to remove 2 letters words:

txt = txt.replace(/(^|[^a-zA-ZΆΈ-ώἀ-ῼ\n])([a-zA-ZΆΈ-ώἀ-ῼ]{2})(?![a-zA-ZΆΈ-ώἀ-ῼ])/gm, '\1');
AD7six

You can use \S

Rather than write a match for "word characters plus these characters" it may be appropriate to use a regex that matches not-whitespace:

\S

It's broader in scope, but simpler to write/use.

If that's too broad - use an exclusive list rather than an inclusive list:

[^\s\.]

That is - any character that is not whitespace and not a dot. In this way it's also easy to add to the exceptions.

Don't try to use \b

Word boundaries don't work with none-ascii characters which is easy to demonstrate:

> "yay".match(/\b.*\b/)
["yay"]
> "γaγ".match(/\b.*\b/)
["a"]

Therefore it's not possible to use \b to detect words with greek characters - every character is a matching boundary.

Match 2 character words

The following pattern can be used to match two character words:

pattern = /(^|[\s\.,])(\S{2})(?=$|[\s\.,])/g;

(More accurately: to match two none-whitespace sequences).

That is:

(^|[\s\.,]) - start of string or whitespace/punctuation (back reference 1)
(\S{2})     - two not-whitespace characters (back reference 2)
($|[\s\.,]) - end of string or whitespace/punctuation (positive lookahead)

That pattern can be used like so to remove matching words:

"input string".replace(pattern);

Here's a jsfiddle demonstrating the patterns use on the texts in the question.

Try something like this:

\s[a-zA-ZΆΈ-ώἀ-ῼ]{2}\s
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!