首页 > 解决方案 > 如何在字符串中查找模式并删除所有不匹配的内容

问题描述

我如何从字符串行中删除所有内容并获取与模式匹配的信息?

例如我有一些字符串作为输入:

  1. “blabbl myexample@ex.com”我只想收到电子邮件或
  2. “公司 blbalbal 电话:88 99 99 247 传真:99 88 14 574”我只想要电话号码

我正在使用 Pattern 来检查字符串是否包含电子邮件或号码,但我不知道如何从中删除所有其他字符串并仅获取匹配的内容

一些建议或例子?

int start,end,length;
String text ="bleble blabbl myexample@ex.com blabla"
Pattern emailP = Pattern.compile(".+@.+\\.com");
Matcher matcherEmail =emailP.matcher(text);
if (matcherEmail.find()) {
start=matcherEmail.start();


//substring
tekst=tekst.substring(0,start);
Matcher matcherEmail =emailP.matcher(text);
end=matcherEmail.end();
length=text.length();
tekst=text.substring(end,length);
}

那么,会是这样吗?在匹配模式之前和我需要检查字符串 2 次之后删除所有内容?

标签: javaandroidregex

解决方案


您的正则表达式.+@.+\.com匹配任何字符 1+ 次,包括空格,@再匹配 1+ 字符,包括空格。请注意,它.+是贪婪的,并且会匹配到字符串的末尾,并且匹配的不仅仅是电子邮件地址。

代替删除不是电子邮件地址的一种可能性是匹配并使用它\S来代替.+匹配非空白字符:

\S+@\S+\.com\b

在 Java 中:

String regex = "\\S+@\\S+\\.com\\b";
String text ="bleble blabbl myexample@ex.com blabla";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);

while (matcher.find()) {
    System.out.println(matcher.group(0));
}

正则表达式演示| Java 演示

要获取电话号码,您可以使用带有 捕获组的正则表达式


推荐阅读