Home > front end >  Converting python regex code to kotlin or java
Converting python regex code to kotlin or java

Time:02-05

>>> import re
>>> re.sub(r'(\d )', r'[\1]', '(201) 555-0123')
'([201]) [555]-[0123]'
>>> re.sub(r'(\d )', r'[\1]', '312 345 6789')
'[312] [345] [6789]'

Hello, how can i convert this python regex code to kotlin or java ?

CodePudding user response:

There is no need for explicitly wrap entire regex in parenthesis to place entire match in group 1, since group 0 already does it for us.

In Java your regex can look like

String yourString = "(201) 555-0123";
yourString = yourString.replaceAll("\\d ", "[$0]");
System.out.println(yourString);  //Output: ([201]) [555]-[0123]

yourString = "312 345 6789";
yourString = yourString.replaceAll("\\d ", "[$0]");
System.out.println(yourString);  //Output: [312] [345] [6789]

$x in replacement allows us to reuse part from group x, so $0 uses match from group 0, meaning entire current regex match.

  •  Tags:  
  • Related