[英]Regular Expression to match compound words using only the first word
I am trying to create a regular expression in JS which will match the occurences of box
and return the full compound word 我正在尝试在JS中创建一个正则表达式,以匹配box
并返回完整的复合词
Using the string: 使用字符串:
the box which is contained within a box-wrap has a box-button
I would like to get: 我想得到:
[box, box-wrap, box-button]
Is this possible to match these words only using the string box
? 仅使用字符串box
可以匹配这些单词吗?
This is what I have tried so far but it does not return the results I desire. 到目前为止,这是我一直尝试的结果,但未返回我想要的结果。
http://jsfiddle.net/w860xdme/ 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);
Try this way: 尝试这种方式:
([\w-]*box[\w-]*)
Requested by comments, here is a working example in javascript: 根据评论的要求,这是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);
Hope it helps. 希望能帮助到你。
我将它扔在那里:
(box[\w-]*)+
You can use this regex in JS: 您可以在JS中使用此正则表达式:
var w = "box"
var re = new RegExp("\\b" + w + "\\S*");
This should work, note the 'W' is upper case. 这应该起作用,注意“ W”为大写。
http://www.w3schools.com/jsref/jsref_obj_regexp.asp http://www.w3schools.com/jsref/jsref_obj_regexp.asp
\\Wbox\\W \\ Wbox \\ W
It looks like you're wanting to use the match with a regex. 看起来您想将匹配项与正则表达式一起使用。 Match is a string method that will take a regex as an argument and return an array containing matches. 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.