我对Java很新,但我希望从正则表达式查找中创建一个String变量。但我不太清楚如何。
基本上我需要:previous_identifer = (all the text in nextline up to the third comma);
可能是这样的东西?
previous_identifier = line.split("^(.+?),(.+?),(.+?),");
或者:
line = reader.readLine();
Pattern courseColumnPattern = Pattern.compile("^(.+?),(.+?),(.+?),");
previous_identifier = (courseColumnPattern.matcher(line).find());
但我知道这不会奏效。我该怎么办?
答案 0 :(得分:0)
您可以使用split
返回一个字符串数组,然后使用StringBuilder构建返回字符串。这种方法的一个优点是能够轻松返回前四个字符串,两个字符串,十个字符串等。
int limit = 3, current = 0;
StringBuilder sb = new StringBuilder();
// Used as an example of input
String str = "test,west,best,zest,jest";
String[] strings = str.split(",");
for(String s : strings) {
if(++current > limit) {
// We've reached the limit; bail
break;
}
if(current > 1) {
// Add a comma if it's not the first element. Alternative is to
// append a comma each time after appending s and remove the last
// character
sb.append(",");
}
sb.append(s);
}
System.out.println(sb.toString()); // Prints "test,west,best"
如果你不需要单独使用这三个元素(你真的只想要一个块中的前三个元素),你可以使用带有以下正则表达式的Matcher:
String str = "test, west, best, zest, jest";
// Matches against "non-commas", then a comma, then "non-commas", then
// a comma, then "non-commas". This way, you still don't have a trailing
// comma at the end.
Matcher match = Pattern.compile("^([^,]*,[^,]*,[^,]*)").matcher(str);
if(match.find())
{
// Print out the output!
System.out.println(match.group(1));
}
else
{
// We didn't have a match. Handle it here.
}
答案 1 :(得分:-1)
尝试使用在线正则表达式测试程序来计算正则表达式,我认为你需要更少的括号来获取整个文本,我猜是这样的:
([^,+?],[^,+?],[^,+?])
哪个说,找到除逗号之外的所有内容,然后是逗号,然后是逗号之外的所有内容,然后是逗号,然后是其他不是逗号的内容。我怀疑这可以大大改善,我不是正则表达式专家
然后你的java只需要编译它并匹配你的字符串:
line = reader.readLine();
Pattern courseColumnPattern = Pattern.compile("([^,+?],[^,+?],[^,+?])");
if (previous_identifier.matches()) {
previous_identifier = (courseColumnPattern.matcher(line);
}
答案 2 :(得分:-1)
你的正则表达式可行,但可以更简单地表达。这就是你如何“提取”它:
String head = str.replaceAll("((.+?,){3}).*", "$1");
匹配整个字符串,同时捕获目标,替换是使用对组1的反向引用捕获的输入。
尽管存在downvote,但这可以证明代码有效!
String str = "foo,bar,baz,other,stuff";
String head = str.replaceAll("((.+?,){3}).*", "$1");
System.out.println(head);
输出:
foo,bar,baz,