英文:
String split if the first character is minus then tread it as a negative sign
问题
- sign可以被视为运算符或负号。如果`-`位于开头,则应将其视为负号,并进行字符串中的减法运算。这仅适用于`-`号,而`+`号始终表示加号。如何实现这一点?
输入:
-23-23+4=F1Qa;
+23-23+4=F1Qa;
输出:
["-23","-","23","+","4","=","F","1","Q","a",";"]
["+", "23","-","23","+","4","=","F","1","Q","a",";"]
这是我目前尝试过的内容:
String regx = "(?:# .*? #:? )|(?!^)(?=\\D)|(?<=\\D)(?=\\d-)"
String[] splits = inputString.split(regx);
英文:
-
sign can be treated as operator or negative sign. If -
is located in the start, it shall be treated as the negative sign and a subtraction whiting the string. This is only apply to -
sign while the +
will be always the add sign. How can I achieve this?
input:
-23-23+4=F1Qa;
+23-23+4=F1Qa;
output:
["-23","-","23","+","4","=","F","1","Q","a",";"]
["+", "23","-","23","+","4","=","F","1","Q","a",";"]
This is what I've tried so far
String regx = (?:# .*? #:?)|(?!^)(?=\\D)|(?<=\\D)(?=\\d-)
String[] splits = inputString.split(regx);
答案1
得分: 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "-23-23+4=F1Qa;&";
Pattern pattern = Pattern.compile("^-\\d+|\\d+|\\D");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
Output:
-23
23
+
4
F
1
Q
a
;
Another test:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "+23-23+4=F1Qa;&";
Pattern pattern = Pattern.compile("^-\\d+|\\d+|\\D");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
Output:
23
23
+
4
F
1
Q
a
;
英文:
You can use the regex, ^-\d+|\d+|\D
which means either negative integer in the beginning (i.e. ^-\d+
) or digits (i.e. \d+
) or a non-digit (\D
).
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "-23-23+4=F1Qa;";
Pattern pattern = Pattern.compile("^-\\d+|\\d+|\\D");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
Output:
-23
-
23
+
4
=
F
1
Q
a
;
Another test:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "+23-23+4=F1Qa;";
Pattern pattern = Pattern.compile("^-\\d+|\\d+|\\D");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
Output:
+
23
-
23
+
4
=
F
1
Q
a
;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论