Javascript 正则表达式 - 如何获取大括号之间的文本
我需要获取大括号之间的文本(如果有)。我确实找到了另一篇文章,但从技术上讲,它没有正确回答: 用于提取方形或卷曲之间文本的正则表达式括号
它实际上并没有说明如何实际提取文本。现在我已经了解了:
var cleanStr = "Some random {stuff} here";
var checkSep = "\{.*?\}";
if (cleanStr.search(checkSep)==-1) { //if match failed
alert("nothing found between brackets");
} else {
alert("something found between brackets");
}
如何从字符串中提取“东西”?另外,如果我更进一步,我如何从这个字符串中提取“东西”和“句子”:
var cleanStr2 = "Some random {stuff} in this {sentence}";
干杯!
I need to get the text (if any) between curly brackets. I did find this other post but technically it wasn't answered correctly:
Regular expression to extract text between either square or curly brackets
It didn't actually say how to actually extract the text. So I have got this far:
var cleanStr = "Some random {stuff} here";
var checkSep = "\{.*?\}";
if (cleanStr.search(checkSep)==-1) { //if match failed
alert("nothing found between brackets");
} else {
alert("something found between brackets");
}
How do I then extract 'stuff' from the string? And also if I take this further, how do I extract 'stuff' and 'sentence' from this string:
var cleanStr2 = "Some random {stuff} in this {sentence}";
Cheers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要提取大括号之间的所有匹配项,您可以执行以下操作:
To extract all occurrences between curly braces, you can make something like this:
创建一个“捕获组”来指示您想要的文本。使用 String.replace() 函数将整个字符串替换为捕获组的反向引用。剩下的就是您想要的文本。
Create a "capturing group" to indicate the text you want. Use the String.replace() function to replace the entire string with just the back reference to the capture group. You're left with the text you want.