简体   繁体   English

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

[英]Javascript regex - how to get text between curly brackets

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: 而且如果我进一步考虑,我如何从这个字符串中提取'stuff'和'sentence':

var cleanStr2 = "Some random {stuff} in this {sentence}";

Cheers! 干杯!

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"]

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. 使用String.replace()函数仅使用捕获组的后引用替换整个字符串。 You're left with the text you want. 你留下了你想要的文字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM