Home > Mobile >  How to use java regex to do job like sed?
How to use java regex to do job like sed?

Time:07-14

E.g. I've got an input string:

2   5* 61.2 -(32.5 7)/ 8

I want to split this string into tokens of decimals and operators( -*/and parentheses), remove blanks(space and tab) add commas in between. The expected output:

2, ,5,*,61.2,-,(,32.5, ,7,),/,8

I know I can do this in sed by just one command:

sed -E 's/ |\t//g;s/([-\ \*\/)(])/,\1,/g;s/, /,/g'

My question: how to use java regex to achieve this? I see java regex is more used to "match/filter" known pattern, can it do "edit" just like sed does?

Appreciate your solutions, thanks.

CodePudding user response:

You can do that by iterating over matched positions of your regexp like:

public static void main(String[] args) throws URISyntaxException {
    String input = "2   5* 61.2 -(32.5 7)/ 8";
    Pattern p = Pattern.compile("\\d (?:\\.\\d )?|[() \\-\\*\\/]{1}");
    Matcher m = p.matcher(input);
    while(m.find()){
        System.out.println(m.group());
    }
}

Disclaimer: the regular expression given fits your particular example but might need rework to support more generic cases.

  • Related