如果我有两个字符串.. 说
string1="Hello dear c'Lint and dear Bob"
和
string2="dear"
我想比较字符串并删除匹配子字符串的第一次出现..
以上字符串对的结果是:
你好 c'Lint 和亲爱的 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() +
"\'");
}
最佳答案
您可以或者使用:
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());
}
您可以在此处使用 index
和 string2.length()
非常轻松地报告区域。当然,如果您希望能够匹配正则表达式模式,您应该使用它们。
编辑:如另一个答案中所述,这两个将从 "and_dear_Bob"
中删除 "dear"
留下 "and__Bob"
- 与代表空格的下划线。所以你最终会在单词之间有两个空格。而且它也不强制匹配是一个完整的单词。它完全符合您的描述,但并未给您显然想要的结果。
编辑:
代码输出的首选:Hello c'Lint and dear Bob
其中 Hello 和 c'Lint 中间有两个空白字符。
虽然这段代码:
string result = string1.replaceFirst(Pattern.quote(string2+" "), ""));
摆脱额外的空白字符。
关于Java:如何删除两个字符串之间第一次出现的匹配子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14535221/