-5

I want to generate a regular expression for extracting string tokens from comma separated tokens surrounded with single quotes.

For example: 'ad2&fs'df','sdfsg34fb5bg','rfrg#d,fg'

Here, I want to get the following tokens:

ad2&fs'df
sdfsg34fb5bg
rfrg#d,fg

The tokens can contain alphabets, numbers and special characters including comma and apostrophe (single quote).

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Amrita
  • 1
  • 2

2 Answers2

0

This could will help.

public static void main(String args[]) throws Exception {
    String s=  "'ad2&fs'df','sdfsg34fb5bg','rfrg#d,fg'";
    System.out.println(Arrays.toString(s.split("','|^'|'$")));
}

O/P :

[, ad2&fs'df, sdfsg34fb5bg, rfrg#d,fg]

This code will give you an additional empty String at index 0 because of the first '. You could just ignore it

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

//use this simple regex pattern

public static void main(String[] args) {

    String s = "'ad2&fs'df','sdfsg34fb5bg','rfrg#d,fg'";
    Pattern pattern = Pattern.compile("'(.*)','(.*)','(.*)'");
    Matcher matcher = pattern.matcher(s);
    boolean match = matcher.matches();

    System.out.println(matcher.group(1));
    System.out.println(matcher.group(2));
    System.out.println(matcher.group(3));
}

}

Output is as follows

ad2&fs'df

sdfsg34fb5bg

rfrg#d,fg

hope this helps.

james jelo4kul
  • 839
  • 4
  • 17