如何将键/值组与正则表达式匹配

时间:2015-08-11 18:27:00

标签: java regex

提供以下字符串:

@NAMEONE=any@character@OTHERNAME=any @ character@THIRDNAME=even new lines
are possible

我们如何匹配@NAMEONE=any@character等全名/值对?

我坚持使用此正则表达式(@(?:NAMEONE|OTHERNAME|THIRDNAME)=.+?)+,因为它只匹配@NAMEONE=a@OTHERNAME=a等。使用Java。

2 个答案:

答案 0 :(得分:2)

仅当@的前后字符为非单词字符时,才会匹配任何字符,但不匹配@@

"@(?:NAMEONE|OTHERNAME|THIRDNAME)=(?:\\B@\\B|[^@])*"

DEMO

"(?s)@(?:NAMEONE|OTHERNAME|THIRDNAME)=.*?(?=@(?:NAMEONE|OTHERNAME|THIRDNAME)=|$)"

DEMO

答案 1 :(得分:0)

这是基于变量的uperrcase名称的简短版本:

  

(@ [A-Z] + = +?)(= @ [A-Z] + = | $)

<强>解释
@[A-Z]+=匹配变量名称和=符号
.+? laziely匹配任何字符
(?=@[A-Z]+=|$)变量名称或字符串结尾的正向预测

Java代码:

public static void test()
{
  String str = "@NAMEONE=any @ character@OTHERNAME=any @ character@THIRDNAME=even";
  Matcher matcher = Pattern.compile("(@[A-Z]+=.+?)(?=@[A-Z]+=|$)").matcher(str);
  while (matcher.find()) {
    System.out.println(matcher.group(0));
  }
}

打印

@NAMEONE=any @ character
@OTHERNAME=any @ character
@THIRDNAME=eve

DEMO