java - 如何在字符串中查找模式并删除所有不匹配的内容
问题描述
我如何从字符串行中删除所有内容并获取与模式匹配的信息?
例如我有一些字符串作为输入:
- “blabbl myexample@ex.com”我只想收到电子邮件或
- “公司 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 次之后删除所有内容?
解决方案
您的正则表达式.+@.+\.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));
}
推荐阅读
- python - How to resolve PIL unidentified image error in flask app
- firefox - Firefox 只显示空白页 - 甚至 about:config 也只是白色的
- dynamic-sql - Use stored proc parameters in Select dynamic SQL
- amazon-web-services - Terraform AWS Cloudwatch 警报
- apache-spark - groupby category and sum the count
- java - how to set 2 types of user for a certain app
- loops - In Pug, how to use a variable outside (set for global use) the each loop it is created in?
- html - How can I scrape a child span class using VBA?
- jasper-reports - Jasper Reports: chart based on two columns
- spring-boot - Load Balancing ActimeMQ Artemis in JBoss EAP 7.2.0