如何书写正则,按|分隔,但排除引号中分隔符,将“a|b|"c|d"|e|f”匹配出成这样 a b "c|d" e f

如何书写正则,按|分隔,排除引号中分隔符,将“a|b|"c|d"|e|f”匹配出成这样
a
b
"c|d"
e
f

正反向零宽断言也可以实现,我在html中给你验证了可行:


const str = 'a|b|"c|d"|e|f';
const regex = /(?<="|^)([^"|]+)(?="|$)|(?<=")([^"]+)(?=")/g;
const matches = str.match(regex);
console.log(matches);

html中的完整实例:


<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>csdn正则表达式</title>
</head>
<body>
  <input type="text" id="input" value="a|b|&quot;c|d&quot;|e|f">
  <button onclick="splitString()">Split</button>
  <ul id="output"></ul>
  <script>
    function splitString() {
      const input = document.getElementById('input').value;
      const regex = /(?<="|^)([^"|]+)(?="|$)|(?<=")([^"]+)(?=")/g;
      const matches = input.match(regex);
      const output = document.getElementById('output');
      output.innerHTML = '';
      for (let i = 0; i < matches.length; i++) {
        const li = document.createElement('li');
        li.textContent = matches[i];
        output.appendChild(li);
      }
    }
  </script>
</body>
</html>

http://t.csdn.cn/OTXja

可以参考这个文章

原始字符串“ab|123|b|"c|d"e|f”。如何使用正则pattern和replace属性,将原始字符串中的除字符串"c|d"之外的"|"替换为“北京”,结果:“ab北京123北京b北京"c|d"e北京f”?

因正则零宽断言不能用非定长patten,用程序吧,写个函数

def replace_(s, rep):    
    i = 0
    flag = 0
    snew = ''
    while i < len(s):
        if flag % 2 == 0 and s[i] == '|':
            snew += rep
        else:
            if s[i] == '"':
                flag += 1
            snew += s[i]            
        i += 1
    return snew

s = """ab|123|b|"c|d"e|f"""
res = replace_(s, '北京')
print(res)

源于chatGPT仅供参考


要编写一个正则表达式来按`|`分隔字符串,但排除引号中的分隔符,可以使用以下正则表达式:

```regex
/("[^"]*"|\w+)/g

解释:

  • "[^"]*": 匹配双引号内的任意字符(除了双引号本身),表示引号中的内容。
  • |: 或运算符,用于匹配双引号内的内容或者单词。
  • \w+: 匹配一个或多个字母、数字或下划线,表示单词。

使用该正则表达式进行匹配后,将得到以下结果:

a
b
"c|d"
e
f

这样就成功地排除了引号中的分隔符,并将字符串按照指定的规则进行了分隔。

在具体的编程语言中,您可以使用对应语言的正则表达式引擎来执行上述正则表达式,并获取匹配的结果。

希望这能满足您的需求!如果还有其他问题,请随时提问。

```

排除:[^cd]
完整的应该是这样:[a-f^cd]