我有一个这样的字符串:
String = IDENTIFIER: 115956 LATITUDE: 40.104730 LONGITUDE: -88.228798 DATE RIGHTS
我想只匹配并打印115956 | 40.104730 | -88.228798
。我如何用正则表达式做到这一点?
这是我的代码:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test3
{
private static String REGEX = "\\d+\\.\\d";
private static String INPUT = "IDENTIFIER: 115956 LATITUDE: 40.104730 LONGITUDE: -88.228798 ";
private static String REPLACE = "-";
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // get a matcher object
StringBuffer sb = new StringBuffer();
while(m.find()){
m.appendReplacement(sb,REPLACE);
}
m.appendTail(sb);
System.out.println(sb.toString());
}
}
但我的结果是这样的:IDENTIFIER: 115956 LATITUDE: -04730 LONGITUDE: --28798
。
答案 0 :(得分:1)
你可以使用这样的正则表达式:
IDENTIFIER:\s(\d*)\sLATITUDE:\s(\d*\.?\d*)\sLONGITUDE:\s(.*?)\s
<强> Working demo 强>
匹配信息
MATCH 1
1. [12-18] `115956`
2. [29-38] `40.104730`
3. [50-60] `-88.228798`
您可以像使用此代码一样进行测试:
public static void main(String args[]) {
String line = "IDENTIFIER: 115956 LATITUDE: 40.104730 LONGITUDE: -88.228798 DATE RIGHTS";
String pattern = "IDENTIFIER:\\s(\\d*)\\sLATITUDE:\\s(\\d*\\.?\\d*)\\sLONGITUDE:\\s(.*?)\\s";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find()) {
System.out.println("Found value: " + m.group(1));
System.out.println("Found value: " + m.group(2));
System.out.println("Found value: " + m.group(3));
} else {
System.out.println("NO MATCH");
}
}
答案 1 :(得分:0)
您可以执行字符串replaceAll
,捕获您关注的组:
class Reg {
static String s = "IDENTIFIER: 115956 LATITUDE: 40.104730 LONGITUDE: -88.228798 DATE RIGHTS";
static public void main(String[] args) {
String r = s.replaceAll("IDENTIFIER: ([0-9]+) LATITUDE: ([-+]?(\\d*[.])?\\d+) LONGITUDE: ([-+]?(\\d*[.])?\\d+).*$", "$1 | $2 | $4");
System.out.println(r);
}
}
$ javac Reg.java
$ java Reg
115956 | 40.104730 | -88.228798