I want to give commands using function like structure in string. For example I have three functions:
go() do() hello()
but also these function have bodies that also could contain the same functions.
"go(){do(){go}} do()"
These functions can also use parameters. How can I do this in regex. It is like creating a programming language.
CodePudding user response:
If you want to parse recursive languages with undefined recursion depth you can't use regex that only parses regular languages and is implemented using a Deterministic Finite Automaton.
Use a parser generator like ANTLR instead that suppurts non-regular grammars. It includes grammar files for all kinds of existing programming languages that you can use as example for parsing your own language.
CodePudding user response:
As per my understanding, We are having function calls as a string inside the function. If Yes, we can give a try to this RegEx
.
\w \([^\)]*\)
\w
: matches word characters. i.e. a-z
, A-Z
, 0-9
, including _ (underscore)
.
: matches one or more occurrences of the word characters.
\(
: matches opening round bracket
[^\)]*
: matches zero or more characters except /
and )
\)
: matches closing round bracket
Live Demo (Just for a demo purpose I am using JavaScript, You can make the changes as per the Java) :
const str = "go(){do(){go}} do()";
console.log(str.match(/\w \([^\)]*\)/g)); // ["go()", "do()", "do()"]