jalmen
jalmen

Reputation: 301

Java regex replaceAll not working

regex not working as wanted

Code example:

widgetCSS = "#widgetpuffimg{width:100%;position:relative;display:block;background:url(/images/small-banner/Dog-Activity-BXP135285s.jpg) no-repeat 50% 0; height:220px;} 

someothertext #widgetpuffimg{width:100%;position:relative;display:block;}"

newWidgetCSS = widgetCSS.replaceAll("#widgetpuffimg\\{(.*?)\\}","");

I want all occurrences in the string that match the pattern "#widgetpuffimg{anycharacters}" to be replaced by nothing

Resulting in newWidgetCSS = someothertext

Upvotes: 1

Views: 955

Answers (2)

Narendra Yadala
Narendra Yadala

Reputation: 9664

Update: After edit of question

I think the regex is working properly according to your requirements if you are escaping your { as mentioned below. The exact output I am getting is " someothertext ".

It has to be newWidgetCSS = widgetCSS.replaceAll("#widgetpuffimg\\{(.*?)\\}",""); You need to use \\{ instead of \{ for escaping { properly.

Upvotes: 1

FailedDev
FailedDev

Reputation: 26930

This should work :

String resultString = subjectString.replaceAll("(?s)\\s*#widgetpuffimg\\{.*?\\}\\s*", "");

Explanation :

"\\s" +                // Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
   "*" +                 // Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
"#widgetpuffimg" +    // Match the characters “#widgetpuffimg” literally
"\\{" +                // Match the character “{” literally
"." +                 // Match any single character
   "*?" +                // Between zero and unlimited times, as few times as possible, expanding as needed (lazy)
"}" +                 // Match the character “}” literally
"\\s" +                // Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
   "*"                   // Between zero and unlimited times, as many times as possible, giving back as needed (greedy)

As an added bonus it trims the whitespace.

Upvotes: 1

Related Questions