【问题标题】:Split a string starting with an underscore _ but not end with the same _拆分以下划线 _ 开头但不以相同 _ 结尾的字符串
【发布时间】:2023-03-16 05:20:01
【问题描述】:

我想以_ 开头,但不以相同的_ 结尾

这是我的输入:

const text = "I, ___________________________ (Photographer's Name), hereby grant _____________________________"

我试过了,但它返回多个数组长度:

let re = /_(.*?)_/;
let result = text.split(re);
console.log('result-------->>>>', result);

预期数组:

[
  "I,", 
  "___________________________", 
  " (Photographer's Name), hereby grant ", 
  "_____________________________"
]

【问题讨论】:

  • 我想为_制作自定义标记

标签: javascript arrays regex replace split


【解决方案1】:

此模式_(.*?)_ 匹配一个下划线,后跟最少的字符,直到下一个下划线,这将分割成对 __

由于.*? 是非贪婪的,因此捕获组(也将保留在结果中)将为空。

如果你让它变得贪婪,它会过度匹配,直到最后一次出现 _ 并阻止显示单独的下划线部分。


您可以在捕获组中拆分例如匹配 2 个或更多下划线 (_{2,}) (一个也可以,但您可以相应地指定数字) 以保留您已拆分的值打开,并从数组中删除空条目。

const text = `I, ___________________________ (Photographer's Name), hereby grant _____________________________`;
let re = /(_{2,})/;
let result = text.split(re);
console.log('result-------->>>>', result.filter(Boolean));

【讨论】:

  • 或者,不使用filter,您可以使用/_{2,}|[^_]+/gmatchconsole.log('result-------->>>>', text.match(/_{2,}|[^_]+/g))。如果您需要警惕单个下划线字符,可以使用正则表达式 /(?:(?!_{2}).)+|_{2,}/g
猜你喜欢
  • 1970-01-01
  • 2012-12-03
  • 1970-01-01
  • 2021-11-28
  • 2023-01-30
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多