You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript正则匹配:匹配以左方括号开头但不以右方括号结尾的文本

正则匹配解决方案

直接用这个正则表达式就能满足你的需求:

/\[[^\]]*(?<!\])/g

正则规则拆解

  • \[:精准匹配左方括号[的字面量
  • [^\]]*:匹配任意数量(包括0个)非右方括号]的字符
  • (?<!\]):反向断言,确保匹配内容的结尾不是右方括号
  • g:全局匹配标志,用于找出文本中所有符合条件的子串

示例验证

  1. 输入文本:This is a [Sample text
    匹配结果:[Sample text
  2. 输入文本:This is [again] a [sample text
    匹配结果:[sample text

JavaScript 实际使用示例

const text1 = "This is a [Sample text";
const text2 = "This is [again] a [sample text] and [another test";
const regex = /\[[^\]]*(?<!\])/g;

console.log(text1.match(regex)); // 输出: ["[Sample text"]
console.log(text2.match(regex)); // 输出: ["[another test"]

你之前尝试的正则问题在于:错误混入了[^}]这类无关规则,也没有正确限制结尾不能是],而反向断言(?<!])是实现需求的核心——它能精准排除掉以]结尾的子串。

内容的提问来源于stack exchange,提问作者Abhinav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 22:40:42