Java 如何提取点后的单词
我有一个如下格式显示的字符串Java 如何提取点后的单词,java,Java,我有一个如下格式显示的字符串 String str = "query at.dddimin ntoreturn:1 reslen:1833 nscanned:1 nquery: { like_symbol: \"SC!JNJ\" } nreturned:1 bytes:1817"; 我需要在上面显示的点后面提取单词,这样输出应该是“dddimin” 我试过这样做 String[] result = str.split("\\."); System.out.println(result[1
String str = "query at.dddimin ntoreturn:1 reslen:1833 nscanned:1 nquery: { like_symbol: \"SC!JNJ\" } nreturned:1 bytes:1817";
我需要在上面显示的点后面提取单词,这样输出应该是“dddimin”
我试过这样做
String[] result = str.split("\\.");
System.out.println(result[1]);
但我得到的结果是
dddimin ntoreturn:1 reslen:1833 nscanned:1 nquery: { unique_symbol: "SC!JNJ" } nreturned:1 bytes:1817
任何人都可以告诉我如何在点后获得单词。如果您想使用split()
,您的正则表达式需要同时按点和空格进行拆分,在这种情况下:
int dot = str.indexOf('.')+1;
String result = str.substring(dot,str.substring(dot).indexOf(' '));
String[] result = str.split("\\ |\\.");
assertEquals("dddimin", result[2]);
如果要使用split()
,您的正则表达式需要同时按点和空格进行拆分,在这种情况下:
String[] result = str.split("\\ |\\.");
assertEquals("dddimin", result[2]);
对于解决字符串模式匹配问题的一般方法,考虑使用正则表达式。在下面的代码中,正则表达式
\(\S+)
表示:查找以点开头、后跟一个或多个非空格字符的字符串的匹配项,并捕获组中点后的字符。在Java中,这将编写如下:
Pattern regex = Pattern.compile("\\.(\\S+)");
Matcher match = regex.matcher(str);
if (match.find())
System.out.println(match.group(1));
match.group(1)
表达式将返回预期结果:
dddimin
对于解决字符串模式匹配问题的一般方法,考虑使用正则表达式。在下面的代码中,正则表达式
\(\S+)
表示:查找以点开头、后跟一个或多个非空格字符的字符串的匹配项,并捕获组中点后的字符。在Java中,这将编写如下:
Pattern regex = Pattern.compile("\\.(\\S+)");
Matcher match = regex.matcher(str);
if (match.find())
System.out.println(match.group(1));
match.group(1)
表达式将返回预期结果:
dddimin