Search code examples
javaregexstringreplaceall

Regex match and substitute strings of special look


I have a set of strings that look like this:

"AK Pz 310u PI-13-5","23.02.2015","07:45:00","23.02.2015","09:20:00","False","True","23.02.2015","07:40:00","2","Common","AK Pz 310u PI-13-5","Common"

And using one single regex and replaceAll method I need to get exactly the following string:

2015-02-23 ==> 07:45 AK Pz 310u

I have a regex that matches time and date

((0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012])\.\d\d\d\d)|((([0-1][0-9])|([2][0-3])):([0-5][0-9]):([0-5][0-9]))

I think I should somehow make use of capturing groups. This part of a the string: "AK Pz 310u PI-13-5" always starts with a capital letter and finishes with a number between 1 and 6, so I think it's quite trivial to match that one. But how do I substitute everything the regex matches with the needed look? And how can I insert the ==> sign into the string.replaceAll method? Any ideas?

BTW: probably, if the original task is too difficult, I can create a two-dimensional array of particular capturing groups in regex and then manipulate the output. Maybe you can throw me a hint on how to do this?

Here is the regex101.com link https://regex101.com/r/vT7eK2/3


Solution

  • for php I world recommend this regexp:

    #^"(\w+) (\w+) (\w+) (?:.+?)","(\d+)\.(\d+)\.(\d+)","(\d+):(\d+):(\d+)"(?:.*?)$#i
    

    and replacement pattern:

    $6-$5-$4 ==> $7:$8 $1 $2 $3
    

    I've just tested it on this site https://ru.functions-online.com/preg_replace.html

    I think it would not be difficult to translate this php_replace regexp to java regexp