[Regular Expressions] Find the Start and End of Whole Words

本文介绍了如何使用正则表达式的单词边界( 和 B)进行精确的字符串匹配,特别是针对“整词”搜索的需求。通过示例展示了如何匹配以特定字符串开头或结尾的情况,并提供了实际代码实现。

Regular Expression Word Boundaries allow to perform "whole word only" searches within our source string.

 

 Imaging we have string as follow, and we want to match all the string which start by 'is:'
var str = `This history is his, it is`;

 

The easiest way is using : \b

\b  //catch the whole word;
\bis  // catch the 'is', which in the beginning of the word
is\b  // catch the 'is', which in the end of the word
\bis\b  //catch only 'is', with nothing else

 

Catch start with 'is':

var regex = /\bis/g

 

Catch end with 'is':

var regex = /is\b/g

 

Catch only 'is':

var regex = /\bis\b/g

 

Also '\B' has the oppset meanings with '\b':

\Bis  // catch 'is', which is NOT at the beginng
is\B  // catch 'is', which is NOT at the end
\Bis\B  //catch 'is', which it neither at beginng or end

 

Not at the begining:

var regex = /\Bis/g

 

Not at the end:

var regex = /is\B/g

 

Neither begining nor end:

var regex = /\Bis\B/g

The same effect as previous one.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值