Question

I have a String as param1=HUvguys83789r8==== i have to split this with = delimiter. I have tried with String.split("=") as well as i have used StringUtils too but i cannot split it correctly. Can some one help me out for this.

String parameters = "param1=HUvguys83789r8===="
String[] string = StringUtils.split(parameters, "=");
parameters.split("=");

And i got my output as [param1, HUvguys83789r8]

I need the output as [param1, HUvguys83789r8====]

Was it helpful?

Solution

You really only want to split on the first occurrence of =, so do that

parameters.split("=", 2)

The overloaded split(String, int) javadoc states

If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.

OTHER TIPS

I would use String#indexOf(char ch) like so,

private static String[] splitParam(String in) {
  int p = in.indexOf('=');
  if (p > -1) {
    String key = in.substring(0, p);
    String value = in.substring(p + 1);
    return new String[] {key, value};
  }
  return null;
}

public static void main(String[] args) {
  String parameters = "param1=HUvguys83789r8====";
  System.out.println(Arrays.toString(splitParam(parameters)));
}

Output is

[param1, HUvguys83789r8====]

Just split once using the alternate version of split():

String[] strings = parameters.split("=", 2); // specify max 2 parts

Test code:

String parameters = "param1=HUvguys83789r8====";
String[] strings = parameters.split("=",2);
System.out.println(Arrays.toString(strings));

Output:

[param1, HUvguys83789r8====]

i think you need :

    String parameters = "param1=HUvguys83789r8====";
    String[] string = parameters.split("\\w=\\w");
    String part1 = string[0]; // param
    String part2 = string[1]; // Uvguys83789r8====
    System.out.println(part1);
    System.out.println(part2);

make sure to escape the slashes to make it java compliant

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top