Search code examples
javaregexsplitslash

Regex for splitting word / (slash) word


I really need a regex expert: I need a regex expression (in java) for splitting this examples:

Hello/World (word/word) => Hello,World

Hello/12 (word/number) => Hello,12

15/Hello (number/word) => 15,Hello

12/17 (number/number) => 12/17 (Do not split)

Update:

This is what I tried but it also mark the number/number option https://regex101.com/r/zZ9nO5/2

Thanks


Solution

  • It might not be the most elegant solution but for your requirement you can do it like that:

    (([a-zA-Z]+?)/([a-zA-Z]+))|(([a-zA-Z]+?)/([\d]+))|(([\d]+?)/([a-zA-Z]+))

    It's a check for word / word, word / number and number / word

    replace with the corresponding groups found \2\5\8,\3\6\9

    A simple java program for that would be:

      public static void main(String[] args) {
                String[] stringArray=new String[]{"Hello/World","Hello/12","15/Hello","12/17"}; 
                for(String s:stringArray) {
                    System.out.println(s.replaceAll("(([a-zA-Z]+?)/([a-zA-Z]+))|(([a-zA-Z]+?)/([\\d]+))|(([\\d]+?)/([a-zA-Z]+))", "$2$5$8,$3$6$9"));
                }
            }
    

    Result is:

    Hello,World
    Hello,12
    15,Hello
    12/17