我有代表表中行的字符串,如下所示:
{failures=4, successes=6, name=this_is_a_name, p=40.00}
我创建了一个可以与 Pattern.split()
一起使用的表达式,以获取 String[]
中的所有值:
[\{\,](.*?)\=
在 online regex tester除了结尾 }
之外,它的效果很好。
但是当我实际针对第一行运行该模式时,我得到一个 String[]
,其中第一个元素是空字符串。我只想要每行中的 4 个值(不是键),而不是额外的空值。
Pattern getRowValues = Pattern.compile("[\\{\\,](.*?)\\=");
String[] row = getRowValues.split("{failures=4, successes=6, name=this_is_a_name, p=40.00}");
//CURRENT
//row[0]=> ""
//row[1]=>"4"
//row[2]=>"6"
//row[3]=>"this_is_a_name"
//row[4]=>"40.00}"
//WANT
//row[0]=>"4"
//row[1]=>"6"
//row[2]=>"this_is_a_name"
//row[3]=>"40.00"
最佳答案
String[] parts = getRowValues
// Strip off the leading '{' and trailing '}'
.replaceAll("^\\{|\\}$", "")
// then just split on comma-space
.split(", ");
如果您只想要值:
String[] parts = getRowValues
// Strip off the leading '{' and up to (but no including) the first =,
// and the trailing '}'
.replaceAll("^\\{[^=]*|\\}$", "")
// then just split on comma-space and up to (but no including) the =
.split(", [^=]*");
关于java - 模式分割以获取表示对象的字符串中的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37355627/