Sujju
Sujju

Reputation: 97

replace string content using .* in java

I am trying to capture the '' part and it is possible that the content inside the '<' and '>' symbols may vary. It might also contain some dots. So I'm trying

String Inputstr = "SOME <Module Name> Module";                  
ptrn = Pattern.compile("<.*>", Pattern.DOTALL);
mtch = ptrn.matcher(Inputstr);
if (mtch.matches()) {
    // Do a replacement operation
}

But the problem is that it doesn't go inside the if conditional at all. Help is appreciated.

Upvotes: 1

Views: 101

Answers (3)

mkazma
mkazma

Reputation: 582

It's tidier and more readable to use

Inputstr.replaceAll("<.*>", "replaced text here");

Upvotes: 0

treeno
treeno

Reputation: 2600

You could use

Inputstr.replaceAll("<.*>", replaceText);

that would be a much shorter solution.

By the way:By convention the first letter of variablenames are written in lower case.

Upvotes: 2

aioobe
aioobe

Reputation: 421040

You should use find and not matches. (matches requires the entire string to match.)

String Inputstr = "SOME <Module Name> Module";                  
Pattern ptrn = Pattern.compile("<.*>", Pattern.DOTALL);
Matcher mtch = ptrn.matcher(Inputstr);
if (mtch.find()) {
    System.out.println("The <...> part: " + mtch.group());  // <Module Name>
}

Also, you don't need DOTALL unless you have new-line characters between < and >.

If you actually want to replace the module name with another string, you could do:

String Inputstr = "SOME <Module Name> Module";                  
String outputStr = Inputstr.replaceAll("<.*>", "A-module-name");
                            ^^^^^^^^^^
System.out.println(outputStr);  // "SOME A-module-name Module"

Upvotes: 7

Related Questions