简体   繁体   English

如何使用 JavaScript 解析带有双花括号的字符串?

[英]How can I parse a string with double curly brackets, using JavaScript?

Is there a fast regex method or similar that can take a string and parse it into bits not in double-curly brackets (let's call those "static") and bits that are in double-curly brackets (let's call those "dynamic")?是否有一种快速的正则表达式方法或类似方法可以获取字符串并将其解析为不在双花括号中的位(让我们称之为“静态”)和在双大括号中的位(让我们称之为“动态”)?

For example, input:例如,输入:

Lorem {{ipsum dolor sit}} amet, {consectetur} adipiscing {{elit}}.

Required output:所需输出:

[
  {
    type: "static",
    value: "Lorem "
  },
  {
    type: "dynamic",
    value: "ipsum dolor sit"
  },
  {
    type: "static",
    value: " amet, {consectetur} adipiscing "
  },
  {
    type: "dynamic",
    value: "elit"
  },
  {
    type: "static",
    value: "."
  },
]

My best try so far has been to use /\{*([^{}]+)\}*/g as a regex and loop through using while and exec but it incorrectly identifies any number of curly brackets as dynamic values, as shown here:到目前为止,我最好的尝试是使用/\{*([^{}]+)\}*/g作为正则表达式并循环使用whileexec但它错误地将任意数量的大括号识别为动态值,如此处显示:

 function templateParser(string) { const re = /\{*([^{}]+)\}*/g; const output = []; while (true) { const match = re.exec(string); if (!match) { break; } const [templateItem, templateKey] = match; output.push({ type: templateItem === templateKey ? "static" : "dynamic", value: templateItem === templateKey ? templateItem : templateKey }); } return output; } console.log( templateParser( "Lorem {{ipsum dolor sit}} amet, {consectetur} adipiscing {{elit}}." ) );

Now that I know more about what you are trying to do, this may help:现在我对您正在尝试做的事情有了更多的了解,这可能会有所帮助:

let mystring = 'test {{hello}} goodbye {{foo}} bar {foobar}';
let regex = /{{(.*?)}}/g;

console.log( mystring.match( regex ) );

output输出

["{{hello}}", "{{foo}}"]

it does a lazy match of each string that has double brackets, puts the matches in an array.它对每个带有双括号的字符串进行惰性匹配,将匹配项放入一个数组中。 You could then replace those substrings with modified versions that include the jsx tags, or something similar.然后,您可以将这些子字符串替换为包含 jsx 标记或类似内容的修改版本。

https://jsfiddle.net/u7gkz341/ https://jsfiddle.net/u7gkz341/

Edit:编辑:

 let mystring = 'test {{hello}} goodbye {{foo}} bar {foobar}'; let regex = /{{(.*?)}}/g; let match; let lastMatchIndex = 0; let results = []; while ( ( match = regex.exec( mystring ) ) !== null ) { results.push( mystring.substring( lastMatchIndex, match.index ) ); // adds static content up until match results.push( match[1] ); // adds dynamic matched content lastMatchIndex = regex.lastIndex; } results.push( mystring.substring( lastMatchIndex ) ); // adds static remainder of string console.log( results );

Edit: the other answer deserves the credit for using positive lookahead.编辑:另一个答案应该归功于使用积极的前瞻。 Using that regex, the complete solution would be:使用该正则表达式,完整的解决方案将是:

Array.from(s.matchAll(/{{(.*?)}}|.+?(?={{|$)/g))
  .map(e=>({type: e[1] ? 'dynamic' : 'static', value: e[1] ?? e[0]}))

or using named capturing groups:或使用命名的捕获组:

Array.from(s.matchAll(/{{(?<dynamic>.*?)}}|(?<static>.+?)(?={{|$)/g))
  .flatMap(e=>Object.entries(e.groups))
  .filter(e=>e[1]).map(e=>({type: e[0], value: e[1]}))

Previous answer:上一个答案:

let s = `Lorem {{ipsum dolor sit}} amet, {consectetur} adipiscing {{elit}}.`;
let result = [{a: 0, b: 0}, ...Array.from(s.matchAll(/{{.*?}}/g))
  .map(e=>({a: e.index, b: e.index+e[0].length}))]
  .map((e, i, arr) => [
    {type: 'dynamic', a: e.a, b: e.b},
    {type: 'static', a: e.b, b: i===arr.length-1 ? s.length : arr[i+1].a}
  ])
  .flat().map(o=>({type: o.type, value: s.substring(o.a, o.b)}))
  .filter(e=>e.value.length>0)
  .map(o=>o.type==='static' ? o :
    {type: 'dynamic', value: o.value.substring(2, o.value.length-2)});

What this does is find all of the strings contained within double braces, and then maps them to an array of objects with start and end indices a and b .这样做是找到包含在双括号中的所有字符串,然后将它们映射到具有开始和结束索引ab的对象数组。

Those will be the dynamic ranges.这些将是动态范围。 We then fill in the gaps in the array to get the static ranges.然后我们填充数组中的空白以获得静态范围。

Finally, we clear the empty ranges and trim the double braces from the dynamic strings.最后,我们清除空范围并从动态字符串中修剪双括号。

To distinguish {{ this }} from that an idea to capture this but match that .{{ this }}that区分开来捕获this匹配that的想法。

{{(.*?)}}|.+?(?={{|$)

See this demo at regex101 or the JS-demo at tio.run请参阅 regex101 上的这个演示或 tio.run上的JS 演示

Using exec your values can easily be set according m[1]!=null ( first group matched).使用exec可以根据m[1]!=null轻松设置您的值(第一组匹配)。 Of course this is according to your sample data.当然,这是根据您的示例数据。 Assuming there is not nesting and not guessing anything else.假设没有嵌套,也没有猜测其他任何东西。

暂无
暂无

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

相关问题 如果在 javascript 中的大括号内有任何带方括号的占位符,如何将字符串更改为新字符串? - How can I change a string into new string if it has any placeholders with square brackets inside curly brackets in javascript? 使用带有N个大括号的JavaScript解析字符串 - Parse string using javascript with N number of curly brackets javascript,正则表达式解析大括号中的字符串内容 - javascript, regex parse string content in curly brackets 如何使用 JavaScript 正则表达式获取两个双花括号内的所有文本,包括括号本身? - How do I get all the text inside two double curly brackets using JavaScript regex, including the brackets themselves? 如何通过 js 正则表达式中的双大括号数组正确拆分字符串? - How to split a string correctly by array of double curly brackets in js regex? 如果@字符位于使用JavaScript的字符串的大括号内,如何不显示下拉菜单? - How not to show dropdown menu if the @ char is within the curly brackets in a string using javascript or react? 如何在 Javascript 中使用双方括号 split() 字符串 - How to split() string with double square brackets in Javascript 如何从方括号内的对象解析字符串 - How can I parse a string from an object inside square brackets JavaScript:什么时候可以省略大括号? - JavaScript: When we can omit curly brackets? javascript在双花括号内匹配希伯来语单词 - javascript match hebrew word inside double curly brackets
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM