如何获取字符串中包含嵌套括号的括号中的所有值?

时间:2019-07-03 05:24:02

标签: javascript regex

期望的行为

我有一个输入验证,除其他事项外,它测试长度(< 140 chars)。

我的输入接受减价,我想在长度计算中排除 URL的长度。

例如,显示为:

  

Math.random()

上有很长的链接指向本文

的长度为57个字符,而其实际代码为155个字符,即:

here is a very long link to this article on [Math.random()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random)

需要涵盖的场景如下:

text and [a markdown link](https://google.com)

text (and [a markdown link within parenthesis](https://google.com))

这个问题是关于:

如何获取字符串中包含嵌套括号的括号中的所有值。

我尝试过的事情

我目前解决总体问题的方法是:

  1. 获取字符串中括号内的所有值
  2. 如果以https开头,则创建字符串的副本
  3. 从复制的字符串中删除值
  4. 获取调整后的字符串的长度并在其上进行长度验证

这些是我对第一部分的尝试:

01)

此解决方案仅获得第一个“匹配项”,来源:https://stackoverflow.com/a/12059321

var text = "here is a (very) long link to this article on [Math.random()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random)";

var regExp = /\(([^)]+)\)/;

var matches = regExp.exec(text);
console.log(matches);
// 0: "(very)"
// 1: "very"

02)

此解决方案获取所有匹配项,包括括号在内,来源:https://stackoverflow.com/a/30674943

var text = "here is a (very) long link to this article on [Math.random()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random)";

var regExp = /(?:\()[^\(\)]*?(?:\))/g;

var matches = text.match(regExp);
console.log(matches);
// 0: "(very)"
// 1: "()"
// 2: "(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random)"

但是在嵌套括号中,它不能按预期工作,即:

var text = "text (and [a markdown link within parenthesis](https://google.com))";

var regExp = /(?:\()[^\(\)]*?(?:\))/g;

var matches = text.match(regExp);
console.log(matches);
// ["(https://google.com)"]

03)

这里有一个php正则表达式解决方案似乎与之相关:

https://stackoverflow.com/a/12994041

但是我不知道如何在javascript中实现该正则表达式,即:

preg_match_all('/^\\((.*)\\)[ \\t]+\\((.*)\\)$/', $s, $matches);

2 个答案:

答案 0 :(得分:2)

尝试(?<=\()[^()]+(?=\))

说明:

(?<=\()-积极肯定地说,前提是(

[^()]+-匹配()

以外的任何一个或多个字符

(?=\))-积极肯定地说,接下来是)

Demo

答案 1 :(得分:2)

我将使用正则表达式,该正则表达式也要求方括号中的部分位于括号内的链接之前。

Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "address" violates not-null constraint. Detail: Failing row contains (17, null, null).

确保使用public AuthenticationMiddleware(RequestDelegate next, IAuthenticationSchemeProvider schemes) { if (next == null) { throw new ArgumentNullException(nameof(next)); } if (schemes == null) { throw new ArgumentNullException(nameof(schemes)); } _next = next; Schemes = schemes; } public IAuthenticationSchemeProvider Schemes { get; set; } public async Task Invoke(HttpContext context) { context.Features.Set<IAuthenticationFeature>(new AuthenticationFeature { OriginalPath = context.Request.Path, OriginalPathBase = context.Request.PathBase }); // Give any IAuthenticationRequestHandler schemes a chance to handle the request var handlers = context.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>(); foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync()) { var handler = await handlers.GetHandlerAsync(context, scheme.Name) as IAuthenticationRequestHandler; if (handler != null && await handler.HandleRequestAsync()) { return; } } var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync(); if (defaultAuthenticate != null) { var result = await context.AuthenticateAsync(defaultAuthenticate.Name); if (result?.Principal != null) { context.User = result.Principal; } } await _next(context); } 标志。这还包括一个捕获组,因此您可以将“可见”部分(方括号之间)与其余“不可见”部分区分开来:

        var defaultAuthenticate = await _schemas.GetDefaultAuthenticateSchemeAsync();
        if (defaultAuthenticate != null)
        {
            var result = await context.AuthenticateAsync(defaultAuthenticate.Name);
            if (result?.Principal != null)
                context.User = result.Principal;

            if (result?.Failure != null)
                throw new AuthorizationException(result.Failure.Message);
        }

        await _next(context);
    }
    catch (AuthorizationException ex) when (!context.Response.HasStarted)
    {
        _logger.LogWarning(ex, "Unauthorized access encountered.");

        context.Response.Clear();
        context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
    }

您实际上可以使用/\[([^\]]+)\]\([^)]+\)/g 调用来删除“不可见”部分。这样可以轻松计算可见字符的总数:

g