正则表达式匹配并替换字符串之间的两个字符

时间:2014-01-29 07:40:53

标签: java regex

我有一个字符串String a =“(3e4 + 2e2)sin(30)”;我想把它显示为a =“(3e4 + 2e2)* sin(30)”;

我无法为此编写正则表达式。

6 个答案:

答案 0 :(得分:1)

试试这个replaceAll

a = a.replaceAll("\) *(\\w+)", ")*$1");

答案 1 :(得分:0)

你可以使用这个

String func = "sin";// or any function you want like cos.
String a = "(3e4+2e2)sin(30)";
a = a.replaceAll("[)]" + func, ")*siz");
System.out.println(a);

答案 2 :(得分:0)

我没有尝试,但以下应该有效

String a = "(3e4+2e2)sin(30)";
a = a.replaceAll("[)](\\w+)", ")*$1");
System.out.println(a);

答案 3 :(得分:0)

这应该有效

a = a.replaceAll("\\)(\\s)*([^*+/-])", ") * $2");

答案 4 :(得分:0)

   String input = "(3e4+2e2)sin(30)".replaceAll("(\\(.+?\\))(.+)", "$1*$2"); //(3e4+2e2)*sin(30)

答案 5 :(得分:0)

假设第一个括号内的字符始终采用相似的模式,您可以在要插入字符的位置将此字符串拆分为两个,然后通过附加字符串的前半部分来形成最终字符串,新字符和字符串的后半部分。

        string a = "(3e4+2e2)sin(30)";

        string[] splitArray1 = Regex.Split(a, @"^\(\w+[+]\w+\)");
        string[] splitArray2 = Regex.Split(a, @"\w+\([0-9]+\)$");

        string updatedInput = splitArray2[0] + "*" + splitArray1[1];

        Console.WriteLine("Input = {0}   Output = {1}", a, updatedInput);
相关问题