[英]Extract substring from string - regex
I have a String say: 我有一个字符串说:
<encoded:2,Message request>
Now I want to extract 2
and Message request
from the line above. 现在,我想从上面的行中提取2
和Message request
。
private final String pString = "<encoded:[0-9]+,.*>";
private final Pattern pattern = Pattern.compile(pString);
private void parseAndDisplay(String line) {
Matcher matcher = pattern.matcher(line);
if (matcher.matches()) {
while(matcher.find()) {
String s = matcher.group();
System.out.println("=====>"+s);
}
}
}
This doesn't retrieve it. 这不会检索它。 What is wrong with it 怎么了
You have to define groups in your regex: 您必须在正则表达式中定义组:
"<encoded:([0-9]+),(.*?)>"
or 要么
"<encoded:(\\d+),([^>]*)"
try 尝试
String s = "<encoded:2,Message request>";
String s1 = s.replaceAll("<encoded:(\\d+?),.*", "$1");
String s2 = s.replaceAll("<encoded:\\d+?,(.*)>", "$1");
Try 尝试
"<encoded:([0-9]+),([^>]*)"
Also, as suggested in other comments, use group(1)
and group(2)
另外,如其他注释所建议,请使用group(1)
和group(2)
Try this out : 试试看:
Matcher matcher = Pattern.compile("<encoded:(\\d+)\\,([\\w\\s]+)",Pattern.CASE_INSENSITIVE).matcher("<encoded:2,Message request>");
while (matcher.find()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.