java - 模式分割以获取表示对象的字符串中的所有值

标签 java regex

我有代表表中行的字符串,如下所示:

{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/

相关文章:

java - Java中的队列/链表序列化

PHP/PCRE/正则表达式 : stripping search term appart

java - java中从一行中删除px的正则表达式

java - 无法将 xml 中的值解析为代码 libgdx

regex - 正则表达式密码验证

c++ - 当不存在可选子字符串时,避免匹配中的空元素

ruby - 如何创建一个与 Ruby 中除某些字符串之外的模式匹配的正则表达式?

java - 在 Android Studio 中更改应用名称

java - 霍夫施塔特的 Q 序列

Java 运算符 : |= bitwise OR and assign example