The introduction
The most recent comparison between ^ and $and (? : the pattern) and (? =pattern), for example: For a parenthesis (e.g., 1+2*(2+3)), there is now a ready-made static method calculateFormula(String formala) that implements: Enter any of the four ordinary expressions without parentheses and return the result.
Considering the priority of operation, we need to calculate the subformula 2+3 first, and get the calculation result 5 through calculateFormula(String formala). Finally, replace the subformula 2+3 in the original formula 1+2*(2+3) with 5, and get an equation 1+2*5 without parentheses. Finally, calculateFormula(String formala) is called to get the final result.
To complete the above example, the two most important points are:
- Gets the subexpression enclosed in parentheses
2 + 3
(Note the contents without parentheses) - will
(1 + 2 * 2 + 3)
In the(2 + 3)
(Note the parenthesized content) is replaced by5
Let’s try to get 2+3 by using a regular expression
The regular expression is used to get the subexpression inside the parentheses — (? The use of = the pattern)
To get the 2+3 of 1+2*(2+3), you match the part of the expression enclosed by () and remove () using the expression :(? () < = \ \ [^ \ \ (\ \)] * (? = \ \))
(? <=\\() means to locate the position after the symbol (, note that this is positioning!! Instead of matching.
[^ \ \ (\ \)] * on behalf of the match zero or more than (or) characters, this is to avoid nested, such as, ((2 + 3) + 1) + 1, this time not matching to the characters ((2 + 3) + 1), and will match only to (2 + 3), to ensure that the formula is does not include the parentheses.
(? =\\)) represents positioning to a position preceding the symbol)
(? : the pattern) and (? The difference between = the pattern)
(? :pattern) the matching result contains pattern
(? +pattern) the matching result does not contain pattern
In terms of the final matching effect (? There is no difference between:
- Matching results of regular expressions
Meaning of ^ and $in character matching
For example: 1+2*(2+3), the following is the case:
- Regular expressions using the ^ and $symbols are used for global character matching, i.e.
(1 + 2 * 2 + 3)
Matches the entire content of - A regular expression with the ^ sign is a pair of substrings headed with the original string, which is true for the example above
1, 1 + 2, 1 + 2 *
. Matches with substrings - A regular expression with the $sign is a pair of substrings that end in the original string, which is true for the example above
), 3) + 3)
. Matches with substrings - A regular expression without the ^ and $symbols matches any subcharacter