[英]Regex to get text beween curly brackets
我有某種這種文件
...some other block above also with a { block }
Main: Subroutine( )
{ <--
Include(foo = bar )
Call(foo = bar )
Repeat(foo = ibar )
{
Message("Message = bar number {ibar}" foo )
Something( )
Message("Message = foo {bar}" )
}
Message("Message = again {iterations}" )
For(start = foo , end = bar )
{
Comment( )
}
While(foo )
{
Comment( )
}
Comment( )
} <--
... some other block below also with a { block }
我需要匹配標有 <-- 的父括號之間的所有內容,我想出了這個
/^Main:\s*\w*\(\s*\)\s*\{\s*((?:.*\s*)*?)\}$/gm
但它在第一個嵌套塊的 } 之后停止,我不知道如何到達最后一個括號。
有什么方法可以匹配直到新行前面的大括號?
謝謝!
編輯:也許我應該補充一下,n 嵌套 { } 塊是可能的
許多正則表達式實現不允許用戶遞歸匹配嵌套組。 Javascript 不提供 PCRE 遞歸參數(?R)
,請參見此處。
改為編寫一個小型解析器。
如果要獲取大括號之間的內容,是否可以使用split
方法:
const str = `Main: Subroutine( ) { Include(foo = bar ) Call(foo = bar ) Repeat(foo = ibar ) { Message("Message = bar number {ibar}" foo ) Something( ) Message("Message = foo {bar}" ) } Message("Message = again {iterations}" ) For(start = foo, end = bar ) { Comment( ) } While(foo ) { Comment( ) } Comment( ) } ` const result = str.split(/[{}]+/) console.log(result);
更新 1:
我添加了一些數據以使示例數據更加復雜。
您可以找到所需單詞的起始索引,然后制作 substring 以提取必要的數據:
const str = `Main 1 Main: Subroutine( ) { Include(foo = bar ) Call(foo = bar ) Repeat(foo = ibar ) { Message("Message = bar number {ibar}" foo ) Something( ) Message("Message = foo {bar}" ) } Message("Message = again {iterations}" ) For(start = foo, end = bar ) { Comment( ) } While(foo ) { Comment( ) } Comment( ) } ` const strToFind = `Main: Subroutine( )`; const preparedString = str.substring(str.indexOf(strToFind)); const result = preparedString.split(/[{}]+/) console.log(result);
嵌套構造對於正則表達式來說是一種痛苦,通常最好使用或構建一些解析器來繼續執行此類任務。
話雖如此,這里的情況看起來很簡單,可以與一些簡單的正則表達式匹配。
我將使用類似^Main:\s*\w*\(\s*\)\s*\{ <--[^}]*(?:\}(?! <--)[^}]*)*\} <--$
.
關鍵點:
\{ <--
匹配一個左大括號,后跟所需的標記。[^}]*
匹配任何非閉合花括號。(?:
開始非捕獲匹配,
\}
一個右花括號,(?! <--)
后面沒有標記,[^}]*)
繼續匹配任何非閉合花括號。\} <--
最后匹配標記的右花括號。嘗試這個:
var myString = "Message = {foo} number {bar}"
var reg = /(?<=\{)\w*(?=\})/g
var myArray = [...myString.matchAll(reg)]
console.log(myArray)
// [['foo'],[bar]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.