正则表达式分组无法正常捕获的问题求助
Hey there, let's work through how to extract the groups you need from your formula string. First, let's recap the original expression you're dealing with:
String formula7 = "(^TBC10.Actual.Value_<<Year>> == \"Final\" ? ^FN10101.Actual.Value_<<Year>> : ^INT805.Consensus.Value_<<Year>>) - (^PH2003 + ^PH2005 + ^PH2011 + ^PH2010 + ^PH2837 + ^PH2838 + ^PH2839 + ^PH2006 + ^PH2089)";
Your goal is to capture three core parts:
- The full content inside the first parenthesis
- The subtraction operator (
-) - The full content inside the second parenthesis
Here's a regex pattern that can do this cleanly, plus a breakdown of each group:
^\((.*?)\)\s*(-)\s*\((.*)\)$
Let's break down what each segment does:
^\(: Matches the opening parenthesis at the start of the string (make sure you strip the surrounding quotes from the Java string first)(.*?): This is Group 1, which captures everything inside the first parentheses using non-greedy matching—this ensures it stops at the first closing)instead of going all the way to the last one\)\s*: Matches the closing parenthesis of the first block, plus any whitespace that follows(-): Group 2, captures the subtraction operator directly\s*\(: Matches any whitespace before the opening parenthesis of the second block(.*): Group 3, captures everything inside the second parentheses (greedy matching works here since it's the final part of the string)\)$: Matches the closing parenthesis at the end of the string
When you use this regex in Java (remember to double-escape backslashes, so the pattern string becomes "^\\((.*?)\\)\\s*(-)\\s*\\((.*)\\)$"), you'll get exactly the groups you want:
- Group 1:
^TBC10.Actual.Value_<<Year>> == "Final" ? ^FN10101.Actual.Value_<<Year>> : ^INT805.Consensus.Value_<<Year>> - Group 2:
- - Group 3:
^PH2003 + ^PH2005 + ^PH2011 + ^PH2010 + ^PH2837 + ^PH2838 + ^PH2839 + ^PH2006 + ^PH2089
If you need to split the first parenthesis into even more granular groups (like the condition, true branch, and false branch of the ternary operator), we can adjust the regex further. For example:
^\((.*?)\s*==\s*"Final"\s*\?\s*(.*?)\s*:\s*(.*?)\)\s*(-)\s*\((.*)\)$
This would add three extra groups: the condition (^TBC10.Actual.Value_<<Year>>), the true value (^FN10101.Actual.Value_<<Year>>), and the false value (^INT805.Consensus.Value_<<Year>>), along with the original three core groups.
Just make sure to use a Matcher instance in Java to extract the groups after compiling the pattern—don't forget to call find() before accessing group values!
备注:内容来源于stack exchange,提问作者Basit

