在java问题中替换字符串

时间:2011-04-27 17:12:38

标签: java regex

假设我有一个java源文件保存到String变量中。

String contents = Utils.getTextFromFile(new File(fileName));

并说源文件中有一行文字如此

String x = "Hello World\n";

注意最后的换行符。

在我的代码中,我知道Hello World的存在,但不知道Hello World\n 因此呼吁

String search = "Hello World";
contents = contents.replaceAll(search, "Something Else");
由于该换行符,

将失败。我怎样才能使它在一个或多个换行符的情况下匹配?这可能是我添加到结尾search变量的正则表达式吗?

编辑:

我正在用变量替换字符串文字。我知道文字,但我不知道他们是否有换行符。这是我替换之前的代码示例。对于替换,我知道application running at a time.存在,但不是application running at a time.\n\n

int option = JOptionPane.showConfirmDialog(null,"There is another application running. There can only be one application\n" +
"application running at a time.\n\n" + 
"Press OK to close the other application\n" + 
"Press Cancel to close this application",
"Multiple Instances of weh detected", 
JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE);

这是我替换后的一个例子

int option = JOptionPane.showConfirmDialog(null,"There is another application running. There can only be one application\n" +
"application running at a time.\n\n" + 
"Press OK to close the other application\n" + 
"PRESS_CANCEL_TO_CLOSE",
"MULTIPLE_INSTANCES_OF",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.ERROR_MESSAGE);

请注意,所有没有换行符的文字都会被替换,例如"Multiple Instances of weh Detected"现在是"MULTIPLE_INSTANCES_OF",但所有带有换行符的文字都不会。我想我可以添加一些正则表达式来处理一个或多个新行字符,当它试图替换所有字符时。

5 个答案:

答案 0 :(得分:1)

因为它实际上是一个作为第一个参数传递的正则表达式,你可以尝试这样的第一个参数

String search = "[^]?[H|h]ello [W|w]orld[\n|$]?"

它会在一行的开头和结尾处搜索hello world,而不管是否有。

有点多余,如上所述它应该无关紧要但......显然它确实

尝试它(使它变得漂亮,所以它匹配大写以及常规字母:P ......只是过度使用它)

答案 1 :(得分:1)

如果您只是替换字符串文字,并且您可以替换每个字面值(而不仅仅是第一个),那么您应该使用replace method而不是replaceAll。

你的第一个例子应该改为:

String search = "Hello World";
contents = contents.replace(search, "Something Else");

replaceAll执行正则表达式替换而不是字符串文字替换。这通常较慢,并不是您的用例所必需的。

请注意,这个答案假设尾部换行符可以保留在字符串中(您在评论中已经说过你可以使用)。

答案 2 :(得分:1)

String search = "Hello World\n\n\n";                           
search.replaceAll ("Hello World(\\n*)", "Guten Morgen\1");

\ 1捕获第一组,标记为(...),从左括号开始计算。 \ n +是换行符的\ n,但反斜杠需要在Java中屏蔽,导致两个反斜杠。 *表示0到n,因此它将捕获0,1,2,...换行符。

答案 3 :(得分:0)

正如评论者指出的那样,\ n不应该搞砸了。但是,如果您可以删除新行,则可以尝试:

contents = contents.replaceAll(“search”+“\\ n *”,“Something Else”);

答案 4 :(得分:0)

根据您的问题,您需要通过以下主持人

public String replaceAll(String regex,String replacement)

这两个参数是 -

regex – the regular expression to match
replacement – the string to be substituted for every match

其他一些方法是: -

replace(char oldChar, char newChar)
replace(CharSequence target, CharSequence replacement)
replaceFirst(String regex, String replacement)

示例是

import  java.lang.String;

public class StringReplaceAllExample {

public static void main(String[] args) {

String str = "Introduction 1231 to  124 basic 1243 programming 34563 concepts 5455";

String Str1 = str.replaceAll("[0-9]+", "");

System.out.println(Str1);

Str1 = str.replaceAll("[a-zA-Z]+", "Java");

System.out.println(Str1);

}

}