【问题标题】:Regex: split string by character except if inside quotes or double quotes [duplicate]正则表达式:按字符拆分字符串,除非在引号或双引号内[重复]
【发布时间】:2020-11-06 16:40:48
【问题描述】:

我需要使用分隔符(在我的示例中为 =)拆分字符串,除非此字符在引号或双引号内

我成功地使用\=+(?=(?:(?:[^']*'){2})*[^']*$) 在单引号内或在双引号内使用\=+(?=(?:(?:[^"]*"){2})*[^"]*$) 成功地做到了这一点,但不是两者都适用,什么是合适的正则表达式?

奖励:如果字符不在字符 ` 内时也可以拆分,那就完美了:)

我需要什么:

编辑: Javascript 示例重现 (https://jsfiddle.net/cgnorhm0/)

function splitByCharExceptInsideString(str, delimiterChar) {
    // split line by character except when it is inside quotes
    const escapedChar = delimiterChar.replace(/[-[\]{}()*+!<=:?./\\^$|#\s,]/g, "\\$&");
    const regSplit = new RegExp(escapedChar + `+(?=(?:(?:[^']*'){2})*[^']*$)`);
    const splits = str.split(regSplit);
    return splits ;
}

const testStr = `image.inside {
    sshagent(credentials: ['ssh-creds']) {
        env.GIT_SSH_COMMAND="ssh -T -o StrictHostKeyChecking=no"
        env.GIT_SSH_COMMAND2='ssh -T -o StrictHostKeyChecking=no'
    }
}`;
const delimiterChar = '=';

const splitLs = splitByCharExceptInsideString(testStr,delimiterChar);
console.log(splitLs);

【问题讨论】:

  • 为什么不尝试另一种方法来拆分字符串。
  • 如果你有一个,我会全神贯注:)
  • 你能把你的测试字符串作为代码发布吗?
  • 这是一个很难回答的问题。 See more discussion here
  • 我将测试字符串添加为代码

标签: javascript regex string quotes double-quotes


【解决方案1】:

下面的正则表达式查找不在 `、" 或 ' 对内的 = 字符。

const regex = /=(?=.*)(?=(?:'.*?'|".*?"|`.*?`).*?)/;

Behavior with your example:

【讨论】:

  • 不工作:/ imgur.com/a/MLNGfwc
  • 很奇怪,我使用的是同一个网站,它对我有用...
  • 你使用的是javascript语法吗?
  • 你能在 regex101 上保存并发布链接吗?
【解决方案2】:

lookahead 和lookbehind 不消耗字符,因此您可以同时使用多个。你可以使用

\=+(?=(?:(?:[^"]*"){2})*[^"]*$)(?=(?:(?:[^']*'){2})*[^']*$)(?=(?:(?:[^`]*`){2})*[^`]*$)

Regex Demo

【讨论】:

  • 当引号不匹配时这将失败:'inside = ' and another = '...
猜你喜欢
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
  • 1970-01-01
  • 2016-08-20
  • 2012-11-24
  • 1970-01-01
  • 1970-01-01
  • 2016-06-24
相关资源
最近更新 更多