0

我有一个文件,我将该文件转换为字符串。现在,每当我试图用像“foobar”这样的小写数据替换一些像“fooBar”这样的驼峰数据时,它就不起作用了。

我试过这两种情况。

   String target = "fooBar and tooohh";
  target = target.replace("foobar", "");
   System.out.println(target);

它给了我这个输出fooBar and tooohh

然后我尝试了这个

String target123 = "fooBar and tooohh";
target123=target123.replace("(?i)foobar", "") ;
System.out.println(target123);

这也给了我相同的输出:-fooBar and tooohh

4

6 回答 6

2

使用String::replaceAllString::replaceFirst方法和正则表达式(?i)foobar

 String replaced = target.replaceAll("(?i)foobar", "");  

或者

String replaced = target.replaceFirst("(?i)foobar", "");

方法String::replace不能与regex

于 2013-06-21T07:27:28.470 回答
1

您正在替换不在“fooBar and tooohh”中的字符串“foobar”。replace 区分大小写,因此如果您想将“fooBar”替换为“”(无),您可以使用:

string target = "fooBar and tooohh";
target = target.replace("fooBar", "");

这将返回:

" and tooohh"

但是,您已要求将所有驼峰式单词小写,在这种情况下您可以这样做:

string target = "fooBar and tooohh";
target = target.toLowerCase();

返回:

"foobar and tooohh"
于 2013-06-21T07:37:48.603 回答
1

正如其他 String 所说,它是不可变的,因此您需要重新分配。

target = target.replace("foobar", "");

使用String.replaceAll您可以使用正则表达式来满足您的需要:

target = target.replaceAll("(?i)foobar", "");

如果要将所有字符串设置为小写,请使用String.toLowerCase

target = target.toLowerCase();
于 2013-06-21T07:31:40.553 回答
1

只需使用String.toLowerCase方法

所以如果你想让整个字符串小写,你可以这样做

String result = test.toLowerCase();

现在,如果您只想将 fooBar 设为小写,则可以执行类似的操作

String temp = "fooBar";
String result = test.replace(temp,temp.toLowerCase());

[只是试图给出一个概念]

于 2013-06-21T07:23:51.050 回答
0

String#toLowerCase是您对问题的回答。

于 2013-06-21T07:27:23.990 回答
0

这是因为在 java 中String不可变的,所以如果你想改变一个Stringwithreplace()方法,你必须像这样重新分配你的变量:

target = target.replace("foobar", "");
于 2013-06-21T07:23:53.190 回答