正则表达式解析java中的字符串

时间:2013-03-07 05:54:58

标签: java regex

我正在使用Java。我需要使用正则表达式解析以下行:

<actions>::=<action><action>|X|<game>|alpha

它应该为我提供令牌<action><action>X<game>

什么样的正则表达式会起作用?

我正在尝试:"<[a-zA-Z]>",但这不会照顾Xalpha

4 个答案:

答案 0 :(得分:5)

您可以尝试这样的事情:

String str="<actions>::=<action><action>|X|<game>|alpha";
str=str.split("=")[1];
Pattern pattern = Pattern.compile("<.*?>|\\|.*?\\|");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group());
}

答案 1 :(得分:1)

你应该有这样的东西:

String input = "<actions>::=<action><action>|X|<game>|alpha";
Matcher matcher = Pattern.compile("(<[^>]+>)(<[^>]+>)\\|([^|]+)\\|(<[^|]+>)").matcher(input);
while (matcher.find()) {
     System.out.println(matcher.group().replaceAll("\\|", ""));
}

如果您想要返回 alpha ,您没有加入,在这种情况下,它不会返回它。

您可以通过将|\\w*添加到我写的正则表达式的末尾来返回alpha。

这将返回:

<action><action>X<game>

答案 2 :(得分:0)

从最初的模式来看,目前尚不清楚你的意思是否确实存在&lt;&gt;无论是否在模式中,我都会采用这种假设。

String pattern="<actions>::=<(.*?)><(.+?)>\|(.+)\|<(.*?)\|alpha";

对于java代码,您可以使用Pattern和Matcher:这是基本的想法:

   Pattern p = Pattern.compile(pattern, Pattern.DOTALL|Pattern.MULTILINE);
   Matcher m = p.matcher(text);
   m.find();
   for (int g = 1; g <= m.groupCount(); g++) {
      // use your four groups here..
   }

答案 3 :(得分:0)

您可以使用以下Java正则表达式:

Pattern pattern = Pattern.compile
       ("::=(<[^>]+>)(<[^>]+>)\\|([^|]+)\\|(<[^>]+>)\\|(\\w+)$");