简体   繁体   中英

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.

Based on How to non-greedy multiple lookbehind matches I added a greedy non-capturing group before the match and a positive look behind,

.*(?<=\s|^)

so now the RegExp is built as follows

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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