有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

正则表达式Java:如何删除两个字符串之间匹配子字符串的第一个匹配项?

如果我有两条线。。 说

string1="Hello dear c'Lint and dear Bob"

string2="dear"

我想比较字符串删除匹配子字符串的第一个匹配项
以上字符串对的结果是:

Hello c'Lint and dear Bob

这是我编写的代码,它接受输入并返回匹配的事件:

System.out.println("Enter your regex: ");
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));

String RegEx = bufferRead.readLine();
Pattern pattern = Pattern.compile(RegEx);
System.out.println("Enter input string to search: ");
bufferRead = new BufferedReader(new InputStreamReader(System.in));
Matcher matcher = pattern.matcher(bufferRead.readLine());

boolean found = false;
while (matcher.find()) {
    System.out.println("I found the text:\"" + matcher.group() +
            "\" starting at index \'" +
            matcher.start() + 
            "\' and ending at index \'" + 
            matcher.end() + 
            "\'");
}

共 (1) 个答案

  1. # 1 楼答案

    您可以使用:

    string result = string1.replaceFirst(Pattern.quote(string2), "");
    

    或者您可以完全避免正则表达式:

    int index = string1.indexOf(string2);
    if (index == -1)
    {
        // Not found. What do you want to do?
    }
    else
    {
        String result = string1.substring(0, index) + 
                        string1.substring(index + string2.length());
    }
    

    您可以在这里使用indexstring2.length()非常轻松地报告区域。当然,如果希望能够匹配正则表达式模式,那么应该使用它们

    编辑:如另一个答案中所述,这两个选项都将从"and_dear_Bob"中删除"dear",留下"and__Bob",下划线表示空格。因此,单词之间会有两个空格。而且这也不会迫使比赛成为一个完整的词。它完全符合你所描述的,但它并没有给你明显想要的结果

    编辑: 代码输出的第一选择:Hello c'Lint and dear Bob 其中Hello和C'LILT中间有两个空白字符。 而此代码:

    string result = string1.replaceFirst(Pattern.quote(string2+" "), ""));
    

    去除额外的空白字符