简体   繁体   中英

replace string between first two occurrence of '&' chars

How can I replace string between first & and next & only:

public class Test02 {


public static void main(String[] args) {
    String xyz = "&axy=asdsd&ram=2 gb4 gb&asd=sdsd&";

    String x =  xyz.replaceAll("&ram=.*&", "&ram=8 gb&");

    System.out.println(x);
    }
}

my input - &axy=asdsd&ram=2 gb4 gb&asd=sdsd& my output - &axy=asdsd&ram=8 gb&

but I want- &axy=asdsd&ram=8 gb&asd=sdsd&

only want to change middle part.

I am making a search filter. If any API for building query exists I would love to know.

Thanks bobble,

this worked... '. ?' instead of '. ' ..

public class Test02 {

public static void main(String[] args) {
    String xyz = "&axy=asdsd&ram=2 gb4 gb&asd=sdsd&";

    String x =  xyz.replaceAll("(&ram=.*?)&", "&ram=8 gb&");

    System.out.println(x);
}

}

now out put-- &axy=asdsd&ram=8 gb&asd=sdsd&

You can use the split method on your String to break it into its tokens with a given delimiter. Then just replace whatever index you want with the new desired value.

Something like this (not tested)

String text = "A&B&C";
String delim = "&";
String[] elements = text.split(delim);
elements[0]= "D";
String result = "";
for (String token : elements) {
    result += token + delim;
}
System.out.println(result.substring(0, result.length() - delim.length())); // "D&B&C"
public static void main(String[] args) {
    String xyz = "&axy=asdsd&ram=2 gb4 gb&asd=sdsd&";
    int firstAndPosition =xyz.indexOf('&',1);
    int secondAndPosition =xyz.indexOf('&',firstAndPosition+1);
    String stringToReplace = xyz.substring(firstAndPosition, secondAndPosition +1);

    //The do your stuff
    String x =  xyz.replaceAll(stringToReplace, "&ram=8 gb&");
    System.out.println(x);
    }
}

You need to use a negated character class [^&] matching any character but a & with a * quantifier (zero or more occurrences) and leverage String#replaceFirst() method to only perform one replacement:

String xyz = "&axy=asdsd&ram=2 gb4 gb&asd=sdsd&";
String x =  xyz.replaceFirst("&ram=[^&]*&", "&ram=8 gb&");
System.out.println(x);
// => &axy=asdsd&ram=8 gb&asd=sdsd&

See IDEONE demo

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