Reputation: 780
String a = "1+2cos(3)+2tan(4)+ln(3)";
String b = a.replaceAll("\) *(\w+)","*");
I want my string to be like
String a = "1+2*cos(3)+2*tan(4)+ln(3)" ;
Upvotes: 1
Views: 95
Reputation: 6527
Try,
String string1 = "1+2cos(30)+2tan(4)+ln(39)";
string1 = string1.replaceAll("([0-9]+)(cos|sin|tan|cot|ln|log)", "$1*$2");
System.out.println(string1);
Upvotes: 0
Reputation: 11524
You can use the positive lookbehinds and lookaheads:
String b = a.replaceAll("(?<=[0-9]+)(?=[a-z]+)", "*");
Translation from Regex into English: insert *
at any position in the string that is preceded by the digits and followed by the letters.
Upvotes: 1
Reputation: 52185
You could use this:
String a = "1+2cos(3)+2tan(4)+ln(3)";
String b = "1+cos(3)+2tan(5)";
System.out.println(a.replaceAll("(\\d+)(cos|tan)","$1*$2"));
System.out.println(b.replaceAll("(\\d+)(cos|tan)","$1*$2"));
Yields:
1+2*cos(3)+2*tan(4)+ln(3)
1+cos(3)+2*tan(5)
The above will match any number which is succeeded by the words cos
or tan
and place it in a group. It then looks for the words cos
or tan
(cos|tan
) and place them in a group (denoted by the round brackets). Once that is done, it will replace all the instances of numbers followed by cos
and tan
with the numbers it matched, followed by *
, followed by whatever items it matched.
Upvotes: 0
Reputation: 16524
Try this:
String b = a.replaceAll("(\d)([a-zA-Z])","$1*$2");
The above will look for a digit next to a alphabet, then using capture groups will insert a *
in between the two.
Upvotes: 3