首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >编写Regex以提取Java中的信息

编写Regex以提取Java中的信息
EN

Stack Overflow用户
提问于 2013-10-17 13:44:01
回答 2查看 71关注 0票数 1

我有两条短信。

1) v1.0 - 80 s200 + 2013-10-17T05:59:59-0700 1TZY6R5HERP7SJRRYDYV 69.71.202.109 7802 41587 495307 30595 HTTP/1.1 POST /gp/ppd

2) access-1080.2013-10-17-05.us-online-cpp-portlet-live-1d-i-752c3b12.us-east-1.phnew.com.gz

我需要从第一个Regex获得这些数据:- 1TZY6R5HERP7SJRRYDYV .Lets调用这个accessId。它总是由20个字符组成,由0-9和upperCase字母表A中的数字组合而成。

我试着使用[A-Z0-9]{20}却没有运气。

代码语言:javascript
复制
Pattern p = Pattern.compile([A-Z0-9]{20});  
Matcher m = p.matcher(myString);

此外,我正在寻找一个与模式匹配的java API,如果它匹配,则给出该模式。

从第二次开始我就需要us-online-cpp-portlet-live-1d-i-752c3b12.us-east-1.phnew.com。我很难破解这件事。

任何帮助都是有用的。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-10-17 13:57:09

您的代码有一些问题--例如,在Pattern初始化中缺少双引号。

下面是你要找的东西的一个例子:

代码语言:javascript
复制
// text for 1st pattern
String text1 = "v1.0 - 80 s200 + 2013-10-17T05:59:59-0700 1TZY6R5HERP7SJRRYDYV 69.71.202.109 7802 41587 495307 30595 HTTP/1.1 POST /gp/ppd";
// text for 2nd pattern
String text2 = "access-1080.2013-10-17-05.us-online-cpp-portlet-live-1d-i-752c3b12.us-east-1.phnew.com.gz";
// 1st pattern - note that the "word" boundary separators are useless here, 
// but they might come in handy if you had alphanumeric Strings longer than 20 characters
Pattern accessIdPattern = Pattern.compile("\\b[A-Z0-9]{20}\\b");
Matcher m = accessIdPattern.matcher(text1);
while (m.find()) {
    System.out.println(m.group());
}
// this is trickier. I assume for your 2nd pattern you want something delimited on the
// left by a dot and starting with 2 lowercase characters, followed by a hyphen, 
// followed by a number of alnums, followed by ".com"
Pattern otherThingie = Pattern.compile("(?<=\\.)[a-z]{2}-[a-z0-9\\-.]+\\.com");
m = otherThingie.matcher(text2);
while (m.find()) {
    System.out.println(m.group());
}

输出:

代码语言:javascript
复制
1TZY6R5HERP7SJRRYDYV
us-online-cpp-portlet-live-1d-i-752c3b12.us-east-1.phnew.com
票数 2
EN

Stack Overflow用户

发布于 2013-10-17 13:48:40

您需要调用Matcher#find(),然后调用Matcher#group(),以获得匹配的结果:

代码语言:javascript
复制
Pattern p = Pattern.compile("[A-Z0-9]{20}");
Matcher m = p.matcher(myString);
String accessId = null;
if (m.find())
   accessId = m.group();
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19428443

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档