我正在解析来自第三方硬件的流的输入。该东西打印出供人类使用的信息。它包括关键字和其他我不关心的字符。我想获取一个流并使用正则表达式查找这些关键字之一的下一次出现。然后我可以做 switch
语句并找出发送的命令。
我无法使用Scanner
类,因为读取被阻止,我无法中断它来停止线程。作为解决方法,我也无法关闭流。
是否有任何库可以用来完成我想要做的事情?我发现Streamflyer ,但这似乎有点矫枉过正,也许不是我想要的。它还建议FilterInputStream ,和FilterReader ,但我不认为这些是我正在寻找的。p>
最佳答案
我有一个开源项目可以帮助解决这个问题,它比基于正则表达式的解决方案快得多:
http://mtimmerm.github.io/dfalex/
概述:
使用 DfaBuilder 制作与每个关键字的
.*KEYWORD
相匹配的 DFA。指定该模式的最简单方法是Pattern.maybeRepeat(CharRange.ALL).then("KEYWORD");
调用 build(),您将得到一个 DfaState。依次为输入的每个字符调用
state=state.getNextState(c)
,每当您到达关键字末尾时,state.getMatch() 都会告诉您您输入的是哪个关键字匹配。
编辑: 这座建筑是这样的:
//The <Integer> here means you want integer results
DfaBuilder<Integer> builder = new DfaBuilder<>();
//Lets say you have a list of keywords:
for (int i=0; i<keywords.size(); ++i)
{
Pattern pat = Pattern.maybeRepeat(CharRange.ALL)
.then(keywords.get(i));
builder.addPattern(pat, i); //when this pattern matches, we get i out
}
DfaState<Integer> startState = builder.build(null);
然后像这样使用它:
DfaState<Integer> st = startState;
for (... each input character c ...)
{
st = st.getNextState(c);
//if this is non-null, then it's the index of the matched keyword
//in the keywords list
Integer match = st.getMatch();
}
关于java - 输入流上的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33356934/