【问题标题】:Regex to get parts of a string正则表达式获取字符串的一部分
【发布时间】:2021-12-10 05:50:46
【问题描述】:

我在不使用 Split 或任何其他类似功能的情况下使用正则表达式来获取字符串的各个部分,这是我的场景:

我有这个文本U:BCCNT.3;GO,我想把不同的部分分开,但是中间的符号我已经设法用这个正则表达式得到第一个/(.+):/.exec(value),这给了我第一个单词直到冒号(: ) 这些是值的不同变体

第二节BCCNT

BCCNT.3;GO -> 没有U:,所以字符串也可能不包含冒号,所以第二部分的逻辑是any text that is between : and . or any text ending with . and nothing infront

第三节.3-> any text starting with a . and ending with nothing or anytext staring with a . and ending with a ; semicolon

第四节;GO->any text starting with a ; and ending with nothing

编辑 最好在单独的变量上,比如

const sectionOne = regex.exec(value);
const sectionTwo = regex.exec(value);
const sectionThree = regex.exec(value);
const sectionFour = regex.exec(value);

并且哪个值与模式不匹配,变量将只是 undefined 或 null 或任何空字符串

【问题讨论】:

    标签: javascript regex string


    【解决方案1】:

    这是一种正则表达式方法,它为每个可能的组件使用 4 个单独的可选捕获组:

    var input = "U:BCCNT.3;GO";
    var re = /^([^:]+:)?([^.]+)?(\.[^;]+)?(;.*)?$/g;
    var m;
    
    m = re.exec(input);
    if (m) {
        console.log(m[1], m[2], m[3], m[4]);
    }

    【讨论】:

    • 好吧,这似乎是正确的,但如果我的输入是这样的,例如var input = "U:BCCNT;GO";,我会得到m[1]=U: m[2]=BCCNT;GO->should be only BCCNT m[3]=undefined->correct because we dont have .3 m[4]=undefined->should have been ;GO
    • 除了正则表达式之外,您可能还需要一些其他逻辑。如果正则表达式组不匹配,它将不可用。
    【解决方案2】:

    类似

    /^(?:([^:]*):)?([^.]*)\.(?:([^;]*);(.*))?/
    

    例如:

    const s = 'U:BCCNT.3;GO';
    const m = s.match(/^(?:([^:]*):)?([^.]*)\.(?:([^;]*);(.*))?/);
    
    console.log(m);

    【讨论】:

    • @Surafel 现在你正在添加额外内容。我的回答是针对原始问题。不幸的是,我现在必须离开电脑。
    • 哦,好吧,对不起,哪个是这个正则表达式的分隔符,也许我可以自己将它们分开 /^(?:([^:]*):)?([^.]*)\. (?:([^;]*);(.*))?/
    猜你喜欢
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    相关资源
    最近更新 更多