简体   繁体   English

正则表达式匹配第二个单词的开头字母

[英]Regular expression to match beginning letter of second word

Consider these names: sathya , subha , selvi, shalini and ashok selvam 考虑以下名称:sathya,subha,selvi,shalini和ashok selvam

I coded as ( 'firstname': new RegExp('^' + req.body[fieldName], 'i') ) which means, If i enter 's' in searchtext box, it will display all the name starts with 's'. 我编码为( 'firstname': new RegExp('^' + req.body[fieldName], 'i') )这意味着,如果我在搜索文本框中输入's',它将显示所有以's开头的名称”。

But in the name ashok selvam, second word is beginning with 's'. 但是,以ashok selvam的名义,第二个单词以“ s”开头。 I want this name also to display when i entered 's' in searchtext box. 当我在搜索文本框中输入“ s”时,我也希望显示该名称。

Which regular expression I have to use to get the result? 我必须使用哪个正则表达式来获得结果?

像这样的东西?

( 'firstname': new RegExp('(^' + req.body[fieldName] + ')|(.*\s+' + req.body[fieldName] + ')', 'i') )

You may use an alternaton non-capturing group (?:^|\\\\s) instead of a mere ^ : 您可以使用替代非捕获组(?:^|\\\\s)而不是仅使用^

new RegExp('(?:^|\\s)' + req.body[fieldName], 'i')

Now, the search will be performed at the start of string or after a whitespace. 现在,搜索将在字符串的开头或空格之后执行。

If the search string may contain special chars, you may need to escape it: 如果搜索字符串可能包含特殊字符,则可能需要对其进行转义:

new RegExp('(?:^|\\s)' + req.body[fieldName].replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'i')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM