简体   繁体   English

用于解析选项字符串的正则表达式

[英]Regular expression to parse option string

I'm using the Java matcher to try and match the following: 我正在使用Java Matcher尝试匹配以下内容:

@tag TYPE_WITH_POSSIBLE_SUBTYPE -PARNAME1=PARVALUE1 -PARNAME2=PARVALUE2: MESSAGE

The TYPE_WITH_POSSIBLE_SUBTYPE consists of letters with periods. TYPE_WITH_POSSIBLE_SUBTYPE由带句点的字母组成。

Every parameter has to consist of letters, and every value has to consist of numerics/letters. 每个参数必须包含字母,每个值都必须包含数字/字母。 There can be 0 or more parameters. 可以有0个或更多参数。 Immediately after the last parameter value comes the semicolon, a space, and the remainder is considered message. 在最后一个参数值到来后,分号,空格和其余部分立即被视为消息。

Everything needs to be grouped. 一切都需要分组。

My current regexp (as a Java literal) is: 我当前的正则表达式(作为Java文字)是:

(@tag)[\\s]+?([\\w\\.]*?)[\\s]*?(-.*=.*)*?[\\s]*?[:](.*)

However, I keep getting all the parameters as one group. 但是,我一直将所有参数作为一组。 How do I get each as a separate group, if it is even possible? 如果有可能,我如何将每个人分成一个单独的小组?

I don't work that much with regexps, so I always mess something up. 我对正则表达式的工作不多,所以我总是搞砸了。

If you want to capture each parameter separately, you have to have a capture group for each one. 如果要分别捕获每个参数,则必须为每个参数都有一个捕获组。 Of course, you can't do that because you don't know how many parameters there will be. 当然,您不能这样做,因为您不知道会有多少个参数。 I recommend a different approach: 我建议使用其他方法:

Pattern p = Pattern.compile("@tag\\s+([^:]++):\\s*(.*)");
Matcher m = p.matcher(s);
if (m.find())
{
  String[] parts = m.group(1).split("\\s+");
  for (String part : parts)
  {
    System.out.println(part);
  }
}
System.out.printf("message: %s%n", m.group(2));

The first element in the array is your TYPE name and the rest (if there are any more) are the parameters. 数组中的第一个元素是您的TYPE名称,其余的(如果有的话)是参数。

Try this out (you may need to add extra '\\' to make it work within a string. 试试看(您可能需要添加额外的'\\'使其在字符串中起作用。

(@tag)\s*(\w*)\s*(-[\w\d]*=[\w\d]*\s*)*:(.*)

By the way, I highly recommend this site to help you build regular expressions: RegexPal . 顺便说一句,我强烈建议您使用此站点来帮助您构建正则表达式: RegexPal Or even better is RegexBuddy ; 甚至更好的是RegexBuddy ; its well worth the $40 if you plan on doing a lot of regular expressions in the future. 如果您打算将来进行很多正则表达式,则值得$ 40。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM