我正在使用Java。我需要分析以下行使用正則表達式:正則表達式在java中解析字符串
<actions>::=<action><action>|X|<game>|alpha
應該給我令牌<action>
,<action>
,X
和<game>
什麼樣的正則表達式是否行得通呢?
我正在嘗試...... "<[a-zA-Z]>"
但這並沒有照顧X
或alpha
。
我正在使用Java。我需要分析以下行使用正則表達式:正則表達式在java中解析字符串
<actions>::=<action><action>|X|<game>|alpha
應該給我令牌<action>
,<action>
,X
和<game>
什麼樣的正則表達式是否行得通呢?
我正在嘗試...... "<[a-zA-Z]>"
但這並沒有照顧X
或alpha
。
你可以嘗試這樣的事情:
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());
}
這包括X與| X |。正則表達式應該忽略| – Dev 2013-03-07 06:21:10
從原始模式中,不清楚你的意思是說模式中是否存在<>,我會遵循該假設。
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..
}
等待,爲什麼alpha在這裏硬編碼。是的,它應該包含「<" and ">」以及不包含這些「<" and ">」結尾的單詞。在上面的示例中,令牌應該是
你應該有這樣的事情:
String input = "<actions>::=<action><action>|X|<game>|alpha";
Matcher matcher = Pattern.compile("(<[^>]+>)(<[^>]+>)\\|([^|]+)\\|(<[^|]+>)").matcher(input);
while (matcher.find()) {
System.out.println(matcher.group().replaceAll("\\|", ""));
}
你沒有specefied如果你想返回或者不是,在這種情況下,它不返回它。
您可以通過在我寫的正則表達式的末尾添加|\\w*
來返回字母。
這將返回:
<action><action>X<game>
您可以使用下面的Java正則表達式:
Pattern pattern = Pattern.compile
("::=(<[^>]+>)(<[^>]+>)\\|([^|]+)\\|(<[^>]+>)\\|(\\w+)$");
如果它匹配'alpha'與否? – 2013-03-07 05:59:18
是的,它也應該包含alpha。 – Dev 2013-03-07 06:14:02