简体   繁体   English

使用正则表达式在 function 中获取 function 名称和代码

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

I am developing an application that reads and visualizes the entered codes.我正在开发一个应用程序来读取和可视化输入的代码。

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

I'm trying to get the struct name and the structures in it我正在尝试获取结构名称和其中的结构

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;
};

I can see Tweet name in match.groups.name , but我可以在match.groups.name中看到Tweet文名称,但是

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

if i want to get this data?如果我想得到这些数据? thanks!谢谢!

You can use this regex to group the struct name and the code inside brackets:您可以使用此正则表达式对结构名称和括号内的代码进行分组:

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

pub struct (\w+) match the struct name pub struct (\w+)匹配结构名称

| the or(|) split the expression, the second expression starts from the first one. or(|)拆分表达式,第二个表达式从第一个开始。

(?<= )((?:.|\s)+)(?=$) match the code inside struct. (?<= )((?:.|\s)+)(?=$)匹配结构中的代码。 Starting from the space after the struct name (?<= ) match all characters ((?:.|\s)+) until reach the end of string (?=$) .从结构名称(?<= )之后的空格开始匹配所有字符((?:.|\s)+)直到到达字符串(?=$)的末尾。

This will parse and return the name and the data structure:这将解析并返回名称和数据结构:

 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: Output:

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

Explanation:解释:

  • \bpub\s+struct\s+ - expect pub struct with word boundary \bpub\s+struct\s+ - 期望带有单词边界的pub struct
  • ([$_\p{ID_Start}][$\p{ID_Continue}]*) - capture group 1 for name ([$_\p{ID_Start}][$\p{ID_Continue}]*) - 捕获名称组 1
  • \s*\{\s* - expect optional whitespace, { , optional whitespace \s*\{\s* - 期望可选空格, { ,可选空格
  • ([^\{]*?) - capture group 2 for data: anything non-greedily that is not { ([^\{]*?) - 捕获第 2 组数据:任何非贪婪的不是{
  • \s*\} - expect optional whitespace and } \s*\} - 期望可选的空格和}

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

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