gpt4 book ai didi

java - 用于在每个字符处拆分但将数字保持在一起的正则表达式

转载 作者:搜寻专家 更新时间:2023-10-31 20:09:59 25 4
gpt4 key购买 nike

我正在寻找一个正则表达式来拆分字符串,如下所示:

String input = "x^(24-3x)";
String[] signs = input.split("regex here");
for (int i = 0; i < signs.length; i++) { System.out.println(sings[i]); }

输出结果为:

"x", "^", "(", "24", "-", "3", "x", ")"

字符串在每个字符处被拆分。但是,如果数字彼此相邻,则它们应保持在一个字符串中。

最佳答案

您可以使用这个基于环视的正则表达式:

String[] signs = input.split("(?<!^)(?=\\D)|(?<=\\D)");

RegEx Demo

正则表达式分解

(?<!^)(?=\\D)  # assert if next char is non-digit and we're not at start
| # regex alternation
(?<=\\D) # assert if previous character is a non-digit

关于java - 用于在每个字符处拆分但将数字保持在一起的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34103906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com