仅用于部分字符串匹配的 Javascript 正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23908057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:47:08  来源:igfitidea点击:

Javascript Regex for a partial string match only

javascriptregexstringmatchpartial

提问by maurya8888

I need to write a JavaScript RegEx that matches only the partial strings in a word.

我需要编写一个只匹配单词中部分字符串的 JavaScript 正则表达式。

For example if I search using the string 'atta'

例如,如果我使用字符串 'atta' 进行搜索

it should return

它应该返回

true for khatta
true for attari
true for navrattan
false for atta

I am not able to figure how to get this done using one RegEx. Thanks!

我不知道如何使用一个 RegEx 来完成这项工作。谢谢!

回答by Lee Kowalkowski

You want to use a non-word boundary \Bhere.

您想在\B此处使用非单词边界。

/\Batta|atta\B/

回答by Per Hornsh?j-Schierbeck

sp00m almost got it right

sp00m 几乎做对了

^(atta.+|.+atta|.+atta.+)$

Fiddle.

小提琴

If whitespace is not allowed you could write

如果不允许使用空格,您可以编写

^(atta[\S]+|[\S]+atta|[\S]+atta[\S]+)$