1

正则表达式没有按要求工作

代码示例:

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

4

2 回答 2

1

更新:编辑问题后

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

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

于 2011-11-02T16:13:01.983 回答
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)

作为一个额外的好处,它修剪了空白。

于 2011-11-02T16:15:06.613 回答