簡體   English   中英

使用正則表達式在 function 中獲取 function 名稱和代碼

[英]Get function name and code inside function with regex

我正在開發一個應用程序來讀取和可視化輸入的代碼。

#[account]
pub struct Tweet {
pub author: Pubkey,
pub timestamp: i64,
pub topic: String,
pub content: String,
}

我正在嘗試獲取結構名稱和其中的結構

const stringCode = `
#[account]
pub struct Tweet {
pub author: Pubkey,
pub timestamp: i64,
pub topic: String,
pub content: String,
}
`;

const functionRegexp =
  /(pub struct\s+)(?<name>[$_\p{ID_Start}][$\u200c\u200c\p{ID_Continue}]*)/u;

const parseCode = () => {
  const match = functionRegexp.exec(stringCode);
  return parseCode;
};

我可以在match.groups.name中看到Tweet文名稱,但是

pub author: Pubkey,
pub timestamp: i64,
pub topic: String,
pub content: String,

如果我想得到這些數據? 謝謝!

您可以使用此正則表達式對結構名稱和括號內的代碼進行分組:

/pub struct (\w+)|(?<= )((?:.|\s)+)(?=$)/gm

pub struct (\w+)匹配結構名稱

| or(|)拆分表達式,第二個表達式從第一個開始。

(?<= )((?:.|\s)+)(?=$)匹配結構中的代碼。 從結構名稱(?<= )之后的空格開始匹配所有字符((?:.|\s)+)直到到達字符串(?=$)的末尾。

這將解析並返回名稱和數據結構:

 const stringCode = ` #[account] pub struct Tweet { pub author: Pubkey, pub timestamp: i64, pub topic: String, pub content: String, } `; const functionRegexp = /\bpub\s+struct\s+([$_\p{ID_Start}][$\p{ID_Continue}]*)\s*\{\s*([^\{]*?)\s*\}/u; const match = functionRegexp.exec(stringCode); console.log('name: ' + match[1]); console.log('data:\n' + match[2]);
Output:

 name: Tweet data: pub author: Pubkey, pub timestamp: i64, pub topic: String, pub content: String,

解釋:

  • \bpub\s+struct\s+ - 期望帶有單詞邊界的pub struct
  • ([$_\p{ID_Start}][$\p{ID_Continue}]*) - 捕獲名稱組 1
  • \s*\{\s* - 期望可選空格, { ,可選空格
  • ([^\{]*?) - 捕獲第 2 組數據:任何非貪婪的不是{
  • \s*\} - 期望可選的空格和}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM