如何修改正则表达式以支持Python的**、//运算符分割算术字符串?
Got it, let's fix this to support Python's ** (exponentiation) and // (floor division) operators! The issue with your current regex is that it treats * and / as single-character tokens, so it splits ** into two separate *s and // into two /s. We need to adjust the regex to recognize these two-character operators as whole units first, then handle the single-character ones.
The Approach
The key idea is to:
- Avoid splitting in the middle of
**or// - Add explicit split points before and after these two-character operators (without breaking them apart)
- Keep supporting all your original single-character operators (
=,+,-,*,/,%,(,))
Updated Code
Here's the adjusted Java code with the modified regex:
String stringM = "variable1 = 1 + 2 ** (4 // (3 + 2) / 6)"; String str = stringM.replaceAll("\\s+", ""); // Regex updated to handle Python's ** and // operators String[] result = str.split("(?<=[-+%=()])|(?=[-+%=()])|(?<!\\*)(?=\\*\\*)|(?<=\\*\\*)(?!\\*)|(?<!/)(?=//)|(?<=//)(?!/)");
Regex Breakdown
Let's unpack the new parts of the regex:
(?<=[-+%=()])|(?=[-+%=()]): Your original logic for single-character operators (we excluded*and/here to handle them separately)(?<!\\*)(?=\\*\\*): Matches the position right before**(ensures the previous character isn't another*, so we don't split in the middle of existing*s)(?<=\\*\\*)(?!\\*): Matches the position right after**(ensures the next character isn't another*)(?<!/)(?=//): Matches the position right before//(previous character isn't/)(?<=//)(?!/): Matches the position right after//(next character isn't/)
Result
When you run this code, the resulting array will be:[variable1, =, 1, +, 2, **, (, 4, //, (, 3, +, 2, ), /, 6, )]
This correctly preserves ** and // as single elements while maintaining all your original splitting behavior for other tokens.
内容的提问来源于stack exchange,提问作者Jbags

