0

I have a string String a = "(3e4+2e2)sin(30)"; and i want to show it as a = "(3e4+2e2)*sin(30)";

I am not able to write a regular expression for this.

2
  • a = a.replaceAll("\)sin", ")*sin"); Commented Jan 29, 2014 at 7:43
  • and what if i have a String a = "(3e4+2e2)cos(30)"; i want to a have regular expression for all the characters not just sin or cos please help Commented Jan 29, 2014 at 7:53

6 Answers 6

1

Try this replaceAll:

a = a.replaceAll("\) *(\\w+)", ")*$1");
Sign up to request clarification or add additional context in comments.

4 Comments

can you explain it a bit please why we use \\w+ and what is $1 and *(\\w+)
\\w+ to match any word after ) and $1 is the back reference of that word (captured group #1) in the replacement string.
*(\\w+) and why you put closure after some space ?
Round parentheses are used to capture the enclosed pattern in a captured group.
0

You can go with this

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);

3 Comments

and what if i have a String a = "(3e4+2e2)cos(30)"; i want to a have regular expression for all the characters not just sin or cos please help
You need to store your function in a variable, then do the replaceAll. see the updates in my answer.
i want only ) will change with )* not any character after and only those ) which are before any character or digit
0

this should work

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

Comments

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

Comments

0

Assuming the characters within the first parenthesis will always be in similar pattern, you can split this string into two at the position where you would like to insert the character and then form the final string by appending the first half of the string, new character and second half of the string.

        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);

Comments

0

I did not try but the following should work

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.