I am writing a regex that will be used for recognizing commands in a string. I have three possible words the commands could start with and they always end with a semi-colon.
I believe the regex pattern should look something like this:
(command1|command2|command3).+;
The problem, I have found, is that since . matches any character and + tells it to match one or more, it skips right over the first instance of a semi-colon and continues going.
Is there a way to get it to stop at the first instance of a semi-colon it comes across? Is there something other than . that I should be using instead?
The issue you are facing with this:
(command1|command2|command3).+;is that the+is greedy, meaning that it will match everything till the last value.To fix this, you will need to make it non-greedy, and to do that you need to add the
?operator, like so:(command1|command2|command3).+?;Just as an FYI, the same applies for the
*operator. Adding a?will make it non greedy.