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 に答える