[英]Replace a string with variable number of spaces with replaceAll
I need to replace a string that could have one or more blank space in its content (at a fixed position) with another string. 我需要替换一个字符串,该字符串的内容(在固定位置)可能有一个或多个空格与另一个字符串。
eg: 例如:
[ 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?
我如何构建表达式以考虑空格?
If you want to allow any whitespace use: 如果要允许任何空格使用:
myString.replaceAll("\\[\\s*(?i)string\\s*\\]", "anotherstring");
If you want to allow only spaces use: 如果您只想让空格使用:
myString.replaceAll("\\[ *(?i)string *\\]", "anotherstring");
Note that you've not escaped the [
and ]
in your regex. 请注意,您没有逃过正则表达式中的
[
和]
。 [
and ]
are regex meta-characters that mark the start and end of a character class respectively. [
和]
是分别标记字符类开头和结尾的正则表达式元字符。
So a [(?i)string]
matches a single character that is one of (
, ?
, i
, )
, s
, t
, r
, i
, n
or g
所以
[(?i)string]
匹配单个字符,它是(
, ?
, i
, )
, s
, t
, r
, i
, n
或g
To match them literally they need to be escaped by placing a \\\\
before them. 要从字面上匹配它们,需要通过在它们之前放置
\\\\
来进行转义。
That expression doesn't work, it only has one character class and would match a single character. 该表达式不起作用,它只有一个字符类,并且匹配单个字符。 You need
"(?i)\\\\[\\\\s*string\\\\s*\\\\]"
. 你需要
"(?i)\\\\[\\\\s*string\\\\s*\\\\]"
。
You need to include the regular expressions to match the spaces as well, that is a whitespace followed by a * which matches any number of instances of the whitespace, including no whitespace. 您需要包含正则表达式以匹配空格,即空格后跟*,它匹配空格的任意数量的实例,包括没有空格。 If you need at least one whitespace, you can replace those with a + sign.
如果您至少需要一个空格,则可以用+号替换它们。
Here's the code for your case: 这是您案例的代码:
String myString="[ String ]";
String result = myString.replaceAll("\\[ *(?i)string *\\]", "anotherstring");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.