简体   繁体   中英

How to replace a text in regex?

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

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM