我是CS的二年级学生,我编写了一个程序,该程序连接到IRC客户端并嗅探线路,等待用户询问“ @TWITTERHANDLE发什么推文?”
该程序会嗅探关键字“ tweeting”,然后运行一个方法,该方法将使用整个输入行查找twitter句柄。
问题是,如果在编译之前我知道该关键字是什么,我知道如何查找该关键字,但是在这种情况下,该关键字可以是任何Twitter句柄,因此我不确定搜索哪种最佳方法这将是。
我尝试了以下操作:inputLine.substring(i + 1,inputLine.indexOf(“”))); 但是它将使用inputLine中的第一个空格作为第二个索引,从而给我IndexOutOfBounds异常。
输入行的示例如下
:TWalk!46774664@gateway/web/freenode/ip.11.222.33.444 PRIVMSG #irchacks :What is @TWalkBot tweeting about right now?
这就是我拥有的代码,它将实际抓住twitter句柄。
/** This method parses the inputLine and returns the Twitter Handle */
public String getTwitterHandle(String inputLine) {
boolean firstAt = true;
char currentChar, tempChar;
for (int i = 0; i < inputLine.length(); i++) {
currentChar = inputLine.charAt(i);
if (currentChar == '@' && firstAt == false) {
for (int j = i; j < inputLine.length(); j++) {
tempChar = inputLine.charAt(j);
if (tempChar == ' ') {
return inputLine.substring(i + 1, j);
}
}
}
else if (currentChar == '@' && firstAt == true) {
firstAt = false;
}
}
return "User Not Found";
}
尽管此代码有效,但我想知道是否有更有效的方法来完成此操作,如果可以,我应该如何看待更改?
谢谢,
汤玛士
是的,您可以使用REGEX使其变得简单而准确:
public class RegExPattern {
public static void main(String[] args) {
String test1 = "What is @TWITTERHANDLE tweeting about?";
String test2 = ":TWalk!46774664@gateway/web/freenode/ip.11.222.33.444 PRIVMSG #irchacks :What is @TWalkBot tweeting about right now?";
Pattern pattern = Pattern.compile(".*@(\\w+).*tweeting.*");
Matcher matcher = pattern.matcher(test1);
if(matcher.find()){
System.out.println(matcher.group(1)); //Sysouts TWITTERHANDLE
}
matcher = pattern.matcher(test2);
if(matcher.find()){
System.out.println(matcher.group(1)); //Sysouts TWalkBot
}
}
}
REGEX上的说明
.*@(\\w+).*tweeting.*
.*@
-贪婪模式会匹配字符串,直到最后出现@符号(\\w+)
-创建第1组,然后是@符号,这是我们的目标,查找长度为1或更大的单词字符.*tweeting.*
-寻找第12组第1组之后出现推文的单词.*
pattern再次用于说明第1组和发推之间的任何字符,第二个用于发推后的任何尾随字符。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句