Javascript 正则表达式 - 如何获取大括号之间的文本

发布于 2024-09-12 11:58:06 字数 647 浏览 5 评论 0原文

我需要获取大括号之间的文本(如果有)。我确实找到了另一篇文章,但从技术上讲,它没有正确回答: 用于提取方形或卷曲之间文本的正则表达式括号

它实际上并没有说明如何实际提取文本。现在我已经了解了:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

紫轩蝶泪 2024-09-19 11:58:06

要提取大括号之间的所有匹配项,您可以执行以下操作:

function getWordsBetweenCurlies(str) {
  var results = [], re = /{([^}]+)}/g, text;

  while(text = re.exec(str)) {
    results.push(text[1]);
  }
  return results;
}

getWordsBetweenCurlies("Some random {stuff} in this {sentence}");
// returns ["stuff", "sentence"]

To extract all occurrences between curly braces, you can make something like this:

function getWordsBetweenCurlies(str) {
  var results = [], re = /{([^}]+)}/g, text;

  while(text = re.exec(str)) {
    results.push(text[1]);
  }
  return results;
}

getWordsBetweenCurlies("Some random {stuff} in this {sentence}");
// returns ["stuff", "sentence"]
心的位置 2024-09-19 11:58:06

创建一个“捕获组”来指示您想要的文本。使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文