InputStream 上的正则表达式
Regex on InputStream
我正在解析来自第 3 方硬件流的输入。这东西打印出人类的信息。它包括关键字和其他我不关心的字符。我想获取流并使用正则表达式查找这些关键字之一的下一次出现。然后我可以做一个 switch
语句并找出发送的命令。
我无法使用 Scanner
class 因为读取被阻止并且我无法中断它来停止线程。作为解决方法,我无法关闭流。
有没有我可以用来做我想做的事情的库?我找到了 Streamflyer, but that seems to be overkill and maybe not what I am looking for. It also suggested FilterInputStream, and FilterReader,但我认为这些不是我要找的。
我有一个开源项目可以帮助解决这个问题,它比基于正则表达式的解决方案快得多:
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();
}
我正在解析来自第 3 方硬件流的输入。这东西打印出人类的信息。它包括关键字和其他我不关心的字符。我想获取流并使用正则表达式查找这些关键字之一的下一次出现。然后我可以做一个 switch
语句并找出发送的命令。
我无法使用 Scanner
class 因为读取被阻止并且我无法中断它来停止线程。作为解决方法,我无法关闭流。
有没有我可以用来做我想做的事情的库?我找到了 Streamflyer, but that seems to be overkill and maybe not what I am looking for. It also suggested FilterInputStream, and FilterReader,但我认为这些不是我要找的。
我有一个开源项目可以帮助解决这个问题,它比基于正则表达式的解决方案快得多:
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();
}