Search code examples
regexregex-lookaroundsregex-negationregex-groupregex-greedy

RegEx for matching digits and failing on special chars


My regex below matches everything with this character after the digits. I want to be able to match only if is present but not if it is followed by or

\(\d{1,}(?:\,?\d{3})*(?:\.\d+)?[ ]?)(!千伏|!千吨|千)\

Currently:

220千伏 (match '220千')
220千吨 (match '220千')
220千 (match '220千')

Expected:

220千伏 (no match)
220千吨 (no match)
220千 (match '220千')

Solution

  • My guess is that you may want to have a list to exclude certain things and have other specific chars, maybe something similar to:

    \d{1,}(?:\,?\d{3})*(?!千伏|千吨)(?:千)
    

    RegEx

    You can design/modify/change your expressions in regex101.com.

    enter image description here

    RegEx Circuit

    You can visualize your expressions in jex.im:

    enter image description here

    JavaScript Test

    const regex = /\d{1,}(?:\,?\d{3})*(?!千伏|千吨)(?:千)/gm;
    const str = `220千伏
    220千吨
    220千`;
    let m;
    
    while ((m = regex.exec(str)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
        }
        
        // The result can be accessed through the `m`-variable.
        m.forEach((match, groupIndex) => {
            console.log(`Found match, group ${groupIndex}: ${match}`);
        });
    }

    Also, you might not want to escape non-metachars, just like Barmar advised, which you could modify this part of your expression:

    \d{1,}(?:\,?\d{3})*