User3518958
User3518958

Reputation: 716

How to use regex groups in Java

I need to replace string 'name' with fullName in the following kind of strings:

software : (publisher:abc and name:oracle)

This needs to be replaced as:

software : (publisher:abc and fullName:xyz)

Now, basically, part "name:xyz" can come anywhere inside parenthesis. e.g.

software:(name:xyz)

I am trying to use groups and the regex I built looks :

(\bsoftware\s*?:\s*?\()((.*?)(\s*?(and|or)\s*?))(\bname:.*?\)\s|:.*?\)$)

Upvotes: 1

Views: 50

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627380

You may use

\b(software\s*:\s*\([^()]*)\bname:\w+

and replace with $1fullName:xyz. See the regex demo and the regex graph:

enter image description here

Details

  • \b - word boundary
  • (software\s*:\s*\([^()]*) - Capturing group 1 ($1 in the replacement pattern is a placeholder for the value captured in this group):
    • software - a word
    • \s*:\s* - a : enclosed with 0+ whitespaces
    • \( - a ( char
    • [^()]* - 0 or more chars other than ( and )
  • \bname - whole word name
  • : - colon
  • \w+ - 1 or more letters, digits or underscores.

Java sample code:

String result = s.replaceAll("\\b(software\\s*:\\s*\\([^()]*)\\bname:\\w+", "$1fullName:xyz");

Upvotes: 1

Related Questions