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

Regular Expression to match compound words using only the first word

本文关键字:复合 单词 正则表达式 单词匹 第一个      更新时间:2023-09-26

我试图在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-]*)

Regex live here.


由注释请求,下面是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*");

RegEx演示

这应该可以工作,注意'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']