1

I have python code as below. I want to convert this code in Java but I am not getting replacement of match.groupdict() in Java. I have applied two different regex for each matchRegex(expr, data) method call in examples below but there may be more regex for every call also. Here is my code:

Python code:

import re

def matchRegex(expr, data):
  match = re.compile(expr).match(data)
  stmt = match.groupdict()
  print("matchRegex() Output = ",stmt)


matchRegex(r'R(?P<rcount>[0-9]*)X?(?P<xdelta>[+\-]?\d*\.?\d*)?Y?(?P<ydelta>[+\-]?\d*\.?\d*)?', "R0004X015Y32")
matchRegex(r'(?P<deprecated>(G54)|(G55))?D(?P<d>\d+)\*', "D10*")

Python Output:

matchRegex() Output =  {'rcount': '0004', 'xdelta': '015', 'ydelta': '32'}
matchRegex() Output  =  {'deprecated': None, 'd': '10'}

My Java Effort :

public Map<String, String> matchRegex(Pattern expr, String data) {
    Matcher match = expr.matcher(data);
    if (match == null) {
        return new HashMap<String, String>(); 
    }else {
        /*
         Dont know how to implement replacement of "stmt = match.groupdict()"            
         */
    }
sandip
  • 70
  • 4
Java-Dev
  • 438
  • 4
  • 20
  • 1
    It seems impossible to do directly in Java. Do you consider _functional_ maps/dictionaries? `UnaryOperator = matcher::group` will transform a group name to a matching result for that group. – Ivan Pavlukhin Mar 30 '19 at 07:02
  • 1
    There could be simpler solution if I understood correctly. If regex patterns are different on every call then you first have to figure out how many different patterns are there. Once you have all the patterns then it can be used in a simple switch case code. – sandip Mar 30 '19 at 10:51
  • see also: https://stackoverflow.com/questions/15588903/get-group-names-in-java-regex – 6harat Jun 19 '20 at 20:30
  • jdk open ticket: https://bugs.openjdk.java.net/browse/JDK-7032377 – 6harat Jun 19 '20 at 20:34

0 Answers0