我有以下字符串:
String sentence = "this is my sentence \"course of math\" of this year";
我需要在这样的引用之后得到第一个单词"
。
在我的例子中,我会得到一个词:course。
答案 0 :(得分:2)
答案 1 :(得分:1)
String sentence = "this is my sentence \"course of math\" of this year";
System.out.println(sentence.replaceAll("(?s)[^\"]*\"(\\w+).*", "$1"));
// Or - if there can be a space after the first quote:
sentence = "this is my sentence \" course of math\" of this year";
System.out.println(sentence.replaceAll("(?s)[^\"]*\"\\s*(\\w+).*", "$1"));
它返回course
,因为该模式会抓取任何字符,直到第一个"
(带[^"]*
),然后匹配引号,然后匹配并捕获1个以上的字母数字或下划线字符(使用(\w+)
),然后匹配任意0个字符到最后(使用.*
),我们只用第1组的内容替换它。
如果有人怀疑是否也可以使用非正则表达式解决方案,那么这里不支持第一个"
和单词之间的空格:
String sentence = "this is my sentence \"course of math\" of this year";
String[] MyStrings = sentence.split(" "); // Split with a space
String res = "";
for(int i=0; i < MyStrings.length; i++) // Iterate over the split parts
{
if(MyStrings[i].startsWith("\"")) // Check if the split chunk starts with "
{
res = MyStrings[i].substring(1); // Get a substring from Index 1
break; // Stop the iteration, yield the value found first
}
}
System.out.println(res);
请参阅IDEONE demo
这是另一个支持第一个"
和下一个词之间的空格:
String sentence = "this is my sentence \" course of math\" of this year";
String[] MyStrings = sentence.split("\"");
String res = MyStrings.length == 1 ? MyStrings[0] : // If no split took place use the whole string
MyStrings[1].trim().indexOf(" ") > -1 ? // If the second element has space
MyStrings[1].trim().substring(0, MyStrings[1].trim().indexOf(" ")): // Get substring
MyStrings[1]; // Else, fetch the whole second element
System.out.println(res);
请参阅another demo