繁体   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