Reputation: 41
Been trying to get this to work all day, but I'm not very good at regular expressions.
A properly formatted string in my case looks like
String s = "10 LET D = 4";
and I'm trying to create a regular expression to make sure that it's properly formatted.
Right now I'm just doing
boolean b = s.matches("[0-9]+ GOTO|LET [a-zA-Z] +|= [0-9]+");
But I know there's something wrong with my GOTO|LET thing, since I kind of just made that up. It didn't work with brackets around it either so I'm a bit lost at this point. Is what I'm trying to do even possible with regex? If not, any other suggestions?
Upvotes: 3
Views: 2477
Reputation: 95479
When it comes to programming languages, you probably want a parser, not a regular expression; however, it really depends on how simple the rules of the language are. You can test out your regular expressions using regexpal (you can find a bunch of regular expression testers by Googling it).
HINT: What you want with regard to the goto and let are parentheses. You probably also want to accept arbitrary amounts of whitespace, so long as there is at least one space. You can do that with "\s+".
Upvotes: 2
Reputation: 72971
Assuming that you allow the syntax GOTO
or LET
, throwing parentheses around these terms should solve the problem.
In addition, I have added grouping (brackets) around +
and =
. It's a quick way to avoid conflict as +
is part of the regex syntax.
boolean b = s.matches("[0-9]+ (GOTO|LET) [a-zA-Z] [+=] [0-9]+");
Note: I agree with other users that if this is part of a larger grammar, then a parser may be better suited.
Upvotes: 5