简体   繁体   中英

Regular expression to match possible words

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?

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.

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+".

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.

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