Java正则表达式替换全部不起作用

时间:2011-11-02 16:11:50

标签: java regex replaceall

正则表达式不按预期工作

代码示例:

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\\{(.*?)\\}","");

我希望字符串中匹配模式“#widgetpuffimg {anycharacters}”的所有匹配项都被替换为

导致newWidgetCSS = someothertext

2 个答案:

答案 0 :(得分:1)

更新:编辑问题后

如果您正在逃避{,我认为正则表达式可以根据您的要求正常运行,如下所述。我得到的确切输出是" someothertext "

必须是newWidgetCSS = widgetCSS.replaceAll("#widgetpuffimg\\{(.*?)\\}",""); 您需要使用\\{代替\{才能正确转义{

答案 1 :(得分:1)

这应该有效:

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

说明:

"\\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)

作为一个额外的奖励它削减了空白。