You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改正则表达式以支持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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:44:15