用字符串中的一些数学字符替换子字符串 - java
Replace substring with some math characters from String - java
我有一个看起来像 String st = "((3-(5-2))+(2*(5-1)))";
的数学表达式,我想 replaceAll
(5-1) 和 4 然后 replaceAll
(2*4) 和 8。 .. 我没有用 4 替换 (5-1) 的问题,但是当我收到 (2*4) 时,因为它有 * 星号,此代码 (st.replaceAll("(2*4)", 8);
) 不起作用!
你能帮我 replaceAll
包含特殊字符的表达式吗?
replaceAll
采用正则表达式,因此您需要使用 \
.
转义 *
因为你在java,你也需要从正则表达式中转义\
Why do you want to use a replaceAll() try replace() instead.
因为 replaceAll() 采用正则表达式并且 * 成为量词。
String st = "((3-(5-2))+(2*(5-1)))";
st = st.replace("(5-1)", "4");
st = st.replace("(2*4)", "8");
System.out.println(st);
您必须在 "*"
之前附加 "\"
,以便在 java 中使用,再使用一个 "\"
.
还需要转义大括号。
public static void main(String[] args) {
String st = "((3-(5-2))+(2*(5-1)))";
st = st.replaceAll("(5-1)", "4");
System.out.println(st);
st = st.replaceAll("(2\*\(4\))", "8");
System.out.println(st);
}
输出
((3-(5-2))+(2*(4)))
((3-(5-2))+(8))
我有一个看起来像 String st = "((3-(5-2))+(2*(5-1)))";
的数学表达式,我想 replaceAll
(5-1) 和 4 然后 replaceAll
(2*4) 和 8。 .. 我没有用 4 替换 (5-1) 的问题,但是当我收到 (2*4) 时,因为它有 * 星号,此代码 (st.replaceAll("(2*4)", 8);
) 不起作用!
你能帮我 replaceAll
包含特殊字符的表达式吗?
replaceAll
采用正则表达式,因此您需要使用 \
.
*
因为你在java,你也需要从正则表达式中转义\
Why do you want to use a replaceAll() try replace() instead.
因为 replaceAll() 采用正则表达式并且 * 成为量词。
String st = "((3-(5-2))+(2*(5-1)))";
st = st.replace("(5-1)", "4");
st = st.replace("(2*4)", "8");
System.out.println(st);
您必须在 "*"
之前附加 "\"
,以便在 java 中使用,再使用一个 "\"
.
还需要转义大括号。
public static void main(String[] args) {
String st = "((3-(5-2))+(2*(5-1)))";
st = st.replaceAll("(5-1)", "4");
System.out.println(st);
st = st.replaceAll("(2\*\(4\))", "8");
System.out.println(st);
}
输出
((3-(5-2))+(2*(4)))
((3-(5-2))+(8))