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
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
|
the or(|) split the expression, the second expression starts from the first one.
(?<= )((?:.|\s)+)(?=$)
match the code inside struct. Starting from the space after the struct name (?<= )
match all characters ((?:.|\s)+)
until reach the end of string (?=$)
.
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]);
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 ([$_\p{ID_Start}][$\p{ID_Continue}]*)
- capture group 1 for name \s*\{\s*
- expect optional whitespace, {
, optional whitespace ([^\{]*?)
- capture group 2 for data: anything non-greedily that is not {
\s*\}
- expect optional whitespace and }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.