【问题标题】:Regex: Negative Lookbehind + Lookahead in Javascript正则表达式:Javascript 中的负后瞻 + 前瞻
【发布时间】:2018-02-28 19:25:53
【问题描述】:

我将尝试围绕这个在服务器端工作的正则表达式。

new RegExp(/(?<!:\s*\w*)\w+(?=\s*[,}])/g)

它遍历一个如下所示的字符串:

{Product{id{$lt:10,$gt:20},title,other,categories{id,name}}}

它匹配所有没有子键或值的键。但这在 Javascript 中不起作用,因为 Javascript 不允许正则表达式的 Lookbehind Parts。我想知道 Javascript 中是否有解决方法。我所阅读的所有内容仅适用于 Lookbehind,而不适用于 Lookbehind+Lookahead。

你可以在这里玩弄它。 regex101.com

编辑:更多信息:此正则表达式是解析器的一部分,它解析简约查询语言 - GraphQL 和 MondoDB-Queries 的嵌合体。

有一个函数可以像

那样输入字符串
{Product{id{$lt:10,$gt:20},title,other,categories{id,name}}}

并输出一个对象。所有实际上没有子键或值的键以“,”或“}”结尾的键都被替换为:true。最后输出如下所示:

{
Product: {
    id: { $lt: 10 },
    title: true,
    categories: {
        name: true
    }
}

}

我正在尝试使其成为客户端。

【问题讨论】:

  • "...这个在服务器端工作的正则表达式...":真的吗?这很奇怪,因为很少有语言接受可变长度的后视。
  • 据我所知,只有 .NET 和 Python 中较新的 regex 模块支持变量后视。
  • @Jan Java 也是如此,但不是无限量词。
  • 如果您添加一些代码,您可以将其转换为有效的解决方案。见this JSFiddle。
  • 我想你可以使用捕获/非捕获组来实现你的目标。不过,您的目标是什么并不完全清楚。您能否提供更多信息,您的输入和预期输出是什么?请给一些真实的代码sn-p(如果你没有给我们const title=...,请不要, title,)

标签: javascript php regex


【解决方案1】:

我认为这可以解决你的问题

const regex = /[{,]\s*\w+(?=[,}])/g
const str = `{Product{id{$lt:10,$gt:20},title,other,categories{id,name}}}`
const result = str.replace(regex, (...a) =>  `${a[0]}:true`)
console.log(result)

【讨论】:

    【解决方案2】:

    不确定您要获得的结果,但这是您的正则表达式
    不使用后向断言。
    如果您有兴趣,整个想法是移动匹配位置
    除了你不想匹配的东西。

    这样做。

     (?:                           # -------------
          ( : \s* \w+ )                 # (1), Move past this
       |                              # or,
          ( \w+ )                       # (2), To get to this
     )                             # -------------
     (?= \s* [,}] )                # Common lookahead assertion
    

    一般情况下,您只需使用 JS 回调功能来找出匹配的内容。

    var regex = /(?:(:\s*\w+)|(\w+))(?=\s*[,}])/g;
    var str = '{Product{id{$lt:10,$gt:20},title,other,categories/{id,name}}}';
    
    var newString = str.replace(
           regex,
           function(match, p1, p2) {  // Callback function
             if (p1) return p1;       // Group 1, return it unchanged
             return p2 + ':true';     // Group 2, modifiy it
           });
    
    console.log(newString);

    输出

    {Product{id{$lt:10,$gt:20},title:true,other:true,categories/{id:true,name:true}}}
    

    【讨论】:

      猜你喜欢
      • 2021-10-11
      • 1970-01-01
      • 2015-09-13
      • 1970-01-01
      • 2011-10-14
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多