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

标签 javascript regex

我正在尝试在 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);

希望有帮助。

关于javascript - 正则表达式仅使用第一个单词来匹配复合词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31812053/

相关文章:

C++ std::regex_replace rgx 和 fmt 参数以在科学记数法中为指数添加前导零?

javascript - 在 JavaScript 中将连字符的名称大写

Java 替换正则表达式不起作用

sql - regexp_like 选择属性字符串包含几个不同单词的行

java - 使用正则表达式在 Eclipse 中查找/替换

javascript - 可以通过将代码加载到 img 元素中来执行代码吗?

javascript - NPM 依赖版本标记为 *

javascript - 动态更改后获取数据属性

javascript - Nodejs请求循环限制

javascript - 错误 : Metadata version mismatch for module found version 4, 预期 3