3

I need to replace a string that could have one or more blank space in its content (at a fixed position) with another string.

e.g:

[   string   ] 

must be replaced with:

anotherstring

(where there could be more or less or none blank spaces between " and string). And also the replacement must be case insenitive. Actually i'm using that expression:

myString.replaceAll("[(?i)string]", "anotherstring"); 

but this only works if there aren't spaces between brackets and string. How can i build an expression to consider also whitespaces?

4

3 に答える 3

4

空白の使用を許可する場合:

myString.replaceAll("\\[\\s*(?i)string\\s*\\]", "anotherstring"); 

スペースのみを許可する場合は、次を使用します。

myString.replaceAll("\\[ *(?i)string *\\]", "anotherstring"); 

正規表現で[andをエスケープしていないことに注意してください。およびは、それぞれ文字クラスの開始と終了を示す正規表現メタ文字です。][]

したがって、aは[(?i)string]、、、、、、、、、、または_ _ _ _ _(?i)string

それらを文字通り一致させるには、\\それらの前に a を配置してエスケープする必要があります。

于 2012-07-31T13:02:45.837 に答える
3

その式は機能しません。文字クラスが 1 つしかなく、1 つの文字に一致します。が必要"(?i)\\[\\s*string\\s*\\]"です。

于 2012-07-31T13:01:33.997 に答える
2

スペースにも一致するように正規表現を含める必要があります。つまり、空白の後に * が続き、空白を含まない空白を含め、空白の任意の数のインスタンスに一致します。少なくとも 1 つの空白が必要な場合は、それらを + 記号に置き換えることができます。

あなたの場合のコードは次のとおりです。

String myString="[      String      ]";
String result = myString.replaceAll("\\[ *(?i)string *\\]", "anotherstring"); 
于 2012-07-31T13:20:13.180 に答える