正则表达式 - 跳过一行或多行
我有以下String
,我需要解析。我正在寻找每个Slot
号码的Board State
。正则表达式 - 跳过一行或多行
Some lines...
SLOT 2 (RP/LC 2): Random Text
MAIN:
PCA:
... More text
Board State is Val
... More text
Some lines...
SLOT 3 (RP/LC 3): Random Text
MAIN:
PCA:
... More text
Board State is Val2
... More text
subslot 0/9/0
目前我有这个。
String regex = "(^SLOT\\s*\\d+).*\\s*.*\\s*.*\\s*.*\\s*.*\\s*.*\\s*.*\\s*.*\\s*.*\\s*.*\\s*.*\\s*.*\\s*.*\\s*.*\\s*.*\\s*.*\\s*.*\\s*.*\\s*(Board.*)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(commandOutput);
while(matcher.find()) {
//Do Something
}
我很难编码需要跳过的行数,但我不喜欢这个,这是糟糕的编程。
是否有可能像做
regex = "(^SLOT\\s*\\d+)(.*\\s*)+(Board.*)"; //This obviously doesn't work. Find slot, then skip one or more lines until it finds Board. I am using \\s instead of \\r\\n because \\s skips tabs as well.
编辑:至于正是我从正则表达式想。将SLOT #
放在一个组中,Board State is Val
放在另一个组中,用于所有SLOTS
。
我会建议使用这种简化的正则表达式你的问题是这样的:
Matcher m = Pattern.compile("SLOT\\s+(\\d+).*?Board\\s+State\\s+is\\s+(\\w+)",
Pattern.DOTALL).matcher(text);
while(m.find())
System.out.printf("Slot is [%s], Board is [%s]%n", m.group(1), m.group(2));
OUTPUT:
Slot is [2], Board is [Val]
Slot is [3], Board is [Val2]
感谢这正是我一直在寻找的! – theking963 2012-01-17 21:08:46
不客气,很高兴它解决了。 – anubhava 2012-01-17 21:12:42
这应该做的工作:我已经使用[^\n\r]
代替.
的情况下,你使用它编译DOTALL
String regex = "(SLOT\\s*\\d+)\\s*\\([^\\)]+\\)\\s*:\\s*\\S*[\n\r](\\s*[^\n\r]+[\n\r])*(Board[^\n\r]*)";
通知。如果没有,您可以轻松更改每[^\n\r]
到.
。
如果(something): something
部分是SLOT \d+
部分后不是强制的,你可以使用变薄之一:
String regex = "(SLOT\\s*\\d+)[^\n\r]*[\n\r](\\s*[^\n\r]+[\n\r])*(Board[^\n\r]*)";
我没有在正则表达式前面使用'^'。我在'group'前面使用它,因为文本中有'subslots',我不想要。我只想要位于行首的“SLOT”。你有一个未封闭的'['和一个未打开的或额外的')'。 – theking963 2012-01-17 20:27:14
你是对的,纠正了答案。 – 2012-01-17 20:29:10
没有匹配。我修改了'regex =“的答案(SLOT \\ s * \\ d +)\\ s * \\([^ \\)] + \\)\\ s *:\\ s * \\ S *( [^ \ n \ r] + [\ n \ r])*(Board)[^ \ n \ r] *“;'(在slot和board中添加group()),因为我需要将它保存在一个组中将其添加到地图。它不会在'while(matcher.find())'里面。我将在我的问题中添加额外的两行以显示代码。 – theking963 2012-01-17 20:36:11
What t分机是你想捕捉,你想跳过什么文字/行? – anubhava 2012-01-17 20:16:18
每个'SLOT'的'Board State',即'SLOT 2 - Board State是Val','SLOT 3 - Board State是Val2'等等。有多个'SLOT',我只以这个为例。 – theking963 2012-01-17 20:28:40