The next token is the first S in the regex. So it continues with the second option, being the second G in the regex. So it knows that this regular expression uses alternation, and that the entire regex has not failed yet. However, the regex engine studied the entire regular expression before starting. The regex engine starts at the first token in the regex, G, and at the first character in the string, S. Let’s see how this works out when the string is SetValue. The obvious solution is Get | GetValue | Set | SetValue. Suppose you want to use a regex to match a list of function names in a programming language: Get, GetValue, Set or SetValue. The consequence is that in certain situations, the order of the alternatives matters. It stops searching as soon as it finds a valid match. I already explained that the regex engine is eager. If we had omitted the parentheses then the regex engine would have searched for a word boundary followed by cat, or, dog followed by a word boundary. This tells the regex engine to find a word boundary, then either cat or dog, and then another word boundary. If we want to improve the first example to match whole words only, we would need to use \b ( cat | dog ) \b. If you want to limit the reach of the alternation, you need to use parentheses for grouping. That is, it tells the regex engine to match either everything to the left of the vertical bar, or everything to the right of the vertical bar. The alternation operator has the lowest precedence of all regex operators. If you want more options, simply expand the list: cat | dog | mouse | fish. If you want to search for the literal text cat or dog, separate both options with a vertical bar or pipe symbol: cat | dog. You can use alternation to match a single regular expression out of several possible regular expressions. I already explained how you can use character classes to match a single character out of several possible characters. Alternation with The Vertical Bar or Pipe Symbol
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |