0

I have the following information:

a). a String in this format [name(label)] bla [name2(label2)] bla [name3(bla3)]

b). Strings name and name2

I need to replace [name(label)] and [name2(label2)] (anything can be between round brackets) with another string (say *), so the result needs to be * bla * bla [name3(bla3)]

Input

[name(label)] bla [name2(label2)] bla [name3(bla3)]

name and name2

Output

* bla * bla [name3(bla3)]

How can I do that using regex in Java?

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
Paul
  • 3,812
  • 10
  • 50
  • 73

2 Answers2

2

regex: "\[name2?\([^\)]+\)\]"

import java.util.regex.*;

public class ValidateDemo
{
    public static void main(String[] args)
    {
        String[] inputA = new String[] {"name", "name2"};
        String tmp = "";

        for (int i = 0; i < inputA.length; i++)
        {
            if(i>0)
                tmp+="|";
            tmp+=inputA[i];
        }
        tmp = "("+tmp+")";
/*
        System.out.println(tmp);
        System.exit(0);
*/
        String regex = "\\["+tmp+"\\([^\\)]+\\)\\]";
        String input = "[name(label)] bla [name2(label2)] bla [name3(bla3)]\n";
        String output = input.replaceAll(regex,"*");
        System.out.println(output);
    }
}
ZiTAL
  • 3,466
  • 8
  • 35
  • 50
1

Try this regex:

\[(name|name2)(\(.*?\))?\]

and replace by your desired thing say *

Regex Demo

Java Sample:

String regex = "\\[(name|name2)(\\(.*?\\)\\)?]";
String string = "[name(label)] bla [name2(label2)] bla [name3(bla3)]\n";
String result = string.replaceAll(regex,"*");
System.out.println(result);

Javascript Sample:

const regex = /\[(name|name2)(\(.*?\))?\]/gm;
const str = `[name(label)] bla [name2(label2)] bla [name3(bla3)]  [name] [name2]`;
const subst = `*`;
const result = str.replace(regex, subst);
console.log(result);
Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43
  • works! can this be improved to replace also `[name]` and `[name2]` (without having those round brackets) with that character `*`? – Paul Apr 11 '17 at 09:52
  • Thanks. There is a small correction that needs to be done to the regex: delete last `\\` - I could not edit your post. – Paul Apr 12 '17 at 07:25