user1464726
user1464726

Reputation: 21

search for string in line

I have problem dealing with a string in a line, For example i have the following lines in a .txt file:

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

I need my code to get the word after "account" (in the first line it's smpp34) and the word "up" (after the "is" word).

I thought about using String.charAt() method but it doesn't work here because the words that I need can be in different places, as shown in the example above.

Upvotes: 0

Views: 346

Answers (3)

prageeth
prageeth

Reputation: 7395

Try RegEx like this.

  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;
  }

Upvotes: 0

Ankit Chhajed
Ankit Chhajed

Reputation: 64

Yeah its best to use regex in this sort of cases..But a simpler method can be used specifically for above case. Simply Try splitting from ) and then read till length of string-5 to length will give you the first word and try similar for second word..

IF and Only if the String pattern above never changes..Else will recommend using regex..

Upvotes: 0

Azodious
Azodious

Reputation: 13872

Try using following methods form String class.

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

Upvotes: 1

Related Questions