繁体   English   中英

正则表达式仅使用第一个单词来匹配复合词

[英]Regular Expression to match compound words using only the first word

我正在尝试在JS中创建一个正则表达式,以匹配box并返回完整的复合词

使用字符串:

the box which is contained within a box-wrap has a box-button

我想得到:

[box, box-wrap, box-button]

仅使用字符串box可以匹配这些单词吗?

到目前为止,这是我一直尝试的结果,但未返回我想要的结果。

http://jsfiddle.net/w860xdme/

var str ='the box which is contained within a box-wrap has a box-button';
var regex = new RegExp('([\w-]*box[\w-]*)', 'g');
document.getElementById('output').innerHTML=str.match(regex);

尝试这种方式:

([\w-]*box[\w-]*)

正则表达式住在这里。


根据评论的要求,这是javascript中的一个有效示例:

 function my_search(word, sentence) { var pattern = new RegExp("([\\\\w-]*" + word + "[\\\\w-]*)", "gi"); sentence.replace(pattern, function(match) { document.write(match + "<br>"); // here you can do what do you want return match; }); }; var phrase = "the box which is contained within a box-wrap " + "has a box-button. it is inbox..."; my_search("box", phrase); 

希望能帮助到你。

我将它扔在那里:

(box[\w-]*)+

您可以在JS中使用此正则表达式:

var w = "box"
var re = new RegExp("\\b" + w + "\\S*");

正则演示

这应该起作用,注意“ W”为大写。

http://www.w3schools.com/jsref/jsref_obj_regexp.asp

\\ Wbox \\ W

看起来您想将匹配项与正则表达式一起使用。 Match是一个字符串方法,它将使用正则表达式作为参数并返回包含匹配项的数组。

var str = "your string that contains all of the words you're looking for";
var regex = /you(\S)*(?=\s)/g;
var returnedArray = str.match(regex);
//console.log(returnedArray) returns ['you', 'you\'re']

暂无
暂无

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

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