【发布时间】:2019-07-03 05:24:02
【问题描述】:
期望的行为
我有一个输入验证,其中包括测试长度 (< 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))
这个问题是关于:
如何获取字符串中括号中的所有值,包括嵌套括号。
我的尝试
我目前对整体问题的处理方法是:
- 获取字符串中括号内的所有值
- 如果有任何以
https开头的字符串,请创建该字符串的副本 - 从复制的字符串中删除值
- 获取调整后字符串的长度并对其进行运行长度验证
这些是我在第一部分的尝试:
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 regex 解决方案似乎是相关的:
https://stackoverflow.com/a/12994041
但我不知道如何在 javascript 中实现该正则表达式,即:
preg_match_all('/^\\((.*)\\)[ \\t]+\\((.*)\\)$/', $s, $matches);
【问题讨论】:
-
我建议找到一个呈现降价的库,然后根据输出进行验证。它可以让您的生活更轻松。
-
嗯,我实际上已经使用markdown-it 来作为编辑器功能,我会查看文档。
标签: javascript regex