javascript - 正则表达式分别匹配方括号中的文本
问题描述
我正在尝试分别匹配方括号中的文本。
// What I did:
const regex = /(\w|\[|\.|,|:|\$)+(?:\s\w+)*(\]|\]|\?|')?/g;
const testString = `This] is a test [string] with [a test that is, obio'u for a $1000?`;
const strings = testString.match(regex);
console.log(strings);
// What I am getting
// [ "This]", "is a test", "[string]", "with", "[a test that is", ", obio'", "u for a", "$1000?" ]
// What I want
// [ "This]", "(a space)is a test(a space)", "[string]", "(a space)with(a space)", "[a test that is, obio'u for a $1000?" ]
我究竟做错了什么?
解决方案
您的正则表达式不允许以空格开头的匹配项。为什么您希望第二个匹配的字符串以空格开头?
这是产生您正在寻找的结果的版本:
const testString = `This] is a test [string] with [a test that is, obio'u for a $1000?`;
const strings = testString.match(/[^\]][^\[\]]*\]?|\]/g);
console.log(strings);
推荐阅读
- python - 计算数百个文件中的唯一 ID?
- c++ - 计算子树中的顶点数
- python - 如何计算png中黑色像素的数量?
- r - x 是否从系列中向下舍入到最接近的指定数值?
- javascript - 数组传播值直到匹配另一个数组长度的长度,以允许数组压缩在一起
- java - extras(通知文本)没有通过
- python - NoReverseMatch:未找到带有参数 '('',)' 的 'update_cart' 的反向。尝试了 1 种模式:['cart/(?P
[\\w-]+)/$'] - python - 熊猫等级归一化 -1 和 1 之间的回报
- python - 我的除法方法不会运行。其他一切都很好
- javascript - React 组件道具的更改是否会导致重新渲染?