[英]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
可以匹配这些单词吗?
到目前为止,这是我一直尝试的结果,但未返回我想要的结果。
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-]*)+
看起来您想将匹配项与正则表达式一起使用。 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.