提供以下字符串:
@NAMEONE=any@character@OTHERNAME=any @ character@THIRDNAME=even new lines
are possible
我们如何匹配@NAMEONE=any@character
等全名/值对?
我坚持使用此正则表达式(@(?:NAMEONE|OTHERNAME|THIRDNAME)=.+?)+
,因为它只匹配@NAMEONE=a
,@OTHERNAME=a
等。使用Java。
答案 0 :(得分:2)
仅当@
的前后字符为非单词字符时,才会匹配任何字符,但不匹配@
和@
。
"@(?:NAMEONE|OTHERNAME|THIRDNAME)=(?:\\B@\\B|[^@])*"
或
"(?s)@(?:NAMEONE|OTHERNAME|THIRDNAME)=.*?(?=@(?:NAMEONE|OTHERNAME|THIRDNAME)=|$)"
答案 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