繁体   English   中英

在行中搜索字符串

[英]search for string in line

我在处理一行中的字符串时遇到问题,例如,在.txt文件中有以下几行:

ussdserver link from host /127.0.0.1:38978(account smpp34) is up|smpp34|2012-10-28 17:02:19
ussdserver link from host localhost/127.0.0.1:8088(account callme) is up|callme|2012-10-28 17:02:20

我需要我的代码来获得“ account”之后的单词(在第一行中为smpp34)和“ up”单词(在“ is”单词之后)。

我考虑过使用String.charAt()方法,但是在这里不起作用,因为我需要的单词可以在不同的地方,如上面的示例所示。

尝试使用以下方法构成String类。

String inputStr = "ussdserver link from host /127.0.0.1:38978(account smpp34) is up|smpp34|2012-10-28 17:02:19";
int index1 = inputStr.indexOf("account");
int index2 = inputStr.indexOf(')',index1);
String accountName = inputStr.substring(index1+8,index2); // you get smpp34

index1 = inputStr.indexOf("|");
index2 = inputStr.lastIndexOf(' ', index1);
String state = inputStr.substring(index2+1, index1) // you get up

是的,在这种情况下最好使用正则表达式..但是一种简单的方法可以专门用于上述情况 只需尝试从拆分,然后读取直到string-5的长度为length即可得到第一个单词,而第二个单词则尝试类似。

IF,并且仅当上面的字符串模式永不更改时。否则,建议使用正则表达式。

像这样尝试RegEx。

  Pattern pattern = Pattern.compile(".*account\\\\s([^\\\\s]*)\\\\)\\\\sis\\\\s([^|]*)|.*"); Matcher matcher = pattern.matcher("ussdserver link from host /127.0.0.1:38978(account smpp34) is up|smpp34|2012-10-28 17:02:19"); while (matcher.find()) { System.out.println(matcher.group(1));//will give you 'smpp34' System.out.println(matcher.group(2));//will give you 'up' return; } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM