简体   繁体   中英

How to match a word without any following or preceding character with RegExp?

I want to create a regex such that

regex = new RegExp(play...);

For string = "I play games" , the result is string.match(regex) = ["play"] ,
but for string = "I am playing games" , the result is string.match(regex) = null .
Ie It matches words that are followed and preceded by spaces or nothing.

使用边界匹配一词:

\\bplay\\b

If you want to match any word characters that come after 'play' but are surrounded by word boundaries like spaces or punctuation, you can use the word boundry matcher \\b and the work character matcher \\w . Try \\bplay\\w*\\b

 var string_1 = "I play games" var string_2 = "I am playing games"; var exp = new RegExp(/\\bplay\\w*\\b/) console.log(string_1.match(exp)); console.log(string_2.match(exp)); 

Add word boundaries on each side of the word to be searched:

 var test = [ "I play games", "I am playing games" ]; console.log(test.map(function (a) { re = new RegExp("\\\\bplay\\\\b"); return a.match(re); })); 

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