简体   繁体   English

正则表达式匹配整个连接字符串

[英]regex match whole joined string

Trying to write a function that will return the whole section of 'conjoined string'.试图编写一个函数来返回“连接字符串”的整个部分。 The only break should be the start or end of the string and a space character唯一的中断应该是字符串的开头或结尾以及一个空格字符

  1. I would like to match a section of "touching" sting.我想匹配一段“感人”的刺痛。

  2. If it contains a matching regex, return the "touching" part如果它包含匹配的正则表达式,则返回“触摸”部分

  3. Else return false否则返回假

    function function_a(string, regex) { try { const reg = new RegExp(/(?:^|\\s)/.source + '(' + /.*?/.source + regex.source + /.*?/.source + ')' + /(?:\\s|$)/.source, regex.flags) const match = string.match(reg) if (match) { return match[1] } else { return false; } } catch (error) { console.error(error); return false; } }

The tests I have are我的测试是

describe('function_a', () => {
    it('should return awordplease', () => {
        const xyz = "mister potter, awordplease";
        expect(function_a(xyz, /(word)/)).toEqual('awordplease');
    });

    it('should return a-man-witha', () => {
        const xyz = "a-man-witha wierd way of sayingit";
        expect(function_a(xyz, /(man|wierd|people)/)).toEqual('a-man-witha');
    });

    it('should return wierd', () => {
        const xyz = "a-man-witha wierd way of sayingit";
        expect(function_a(xyz, /(lady|wierd|people)/)).toEqual('wierd');
    });

    it('should return 3434this__432eed2e-tro_py', () => {
        const xyz = "skdjmdkas 3434this__432eed2e-tro_py wdsds asjbchjzxacuyvdkajsnfrsd";
        expect(function_a(xyz, /(this|that)/)).toEqual('3434this__432eed2e-tro_py');
    });

it('should return skdjmdkas3434select__432eed2e-tro_py', () => {
    const xyz = "skdjmdkas3434select__432eed2e-tro_py";
    expect(function_a(xyz, /(select)/)).toEqual('skdjmdkas3434select__432eed2e-tro_py');
});

}); });

I can't quite get the regex to work out.我不能完全让正则表达式解决。 I think the issue is with the (?:^|\\s) at the start, it matches too much.我认为问题出在 (?:^|\\s) 开始时,它匹配太多。

Based on How to non-greedy multiple lookbehind matches I added a greedy non-capturing group before the match and a positive look behind,基于How to non-greedy multiple lookbehind 匹配,我在比赛前添加了一个贪婪的非捕获组,并在后面添加了一个积极的外观,

.*(?<=\s|^)

so now the RegExp is built as follows所以现在正则表达式构建如下

new RegExp(/(?:.*)(?<=\s|^)/.source + '(' + /.*?/.source + regex.source + /.*?/.source + ')' + /(?:\s|$)/.source, regex.flags)

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

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