简体   繁体   中英

Best way to split strings and get variables from it

Let's say i need to read a log file. Once the log file reach a line where there the status is 'I am an important log' in need to do some stuff with that line.

String exampleOfWhatStrLineReturns ="2016-02-06 10:19:36,410 INFO  [[RequestMappingHandlerMapping]]: I am an important log [123, 21] ...{.....}";

String id = "123";
String anotherValueIWant = "21";
String timestampString = "2016-02-06 10:19:36,410";

What would be the best way to achieve this?

I would suggest using an InputStreamReader to read the file then wrap in a buffered reader as shown in the example. Since you say you know what keyword you are looking for, you can read by like and use 'contains' to identify the line.

How you process the line would again depend on what you already know and what you do not and if the pattern is consistent. If the pattern is consistent, you can try doing a split/tokenize and then concatenating the relevant information.

Where details of the content are already known, use it if possible, to identify the position of occurrence and thus minimize reg-exp usage which will otherwise result in parsing more data than is required (not that its too much of a concern).

If you are using jdk7, you need not be bothered too much about processing string consuming non-gc-able memory because from jdk7 onwards the string is present in the heap .

You can do this as follows:

  1. Extracting TimeStamp

Search for the first occurrence of INFO and then take the sub-string from 0 to the position - 1.

  1. Extracting Id & AnotherValueIWant

Search for the regex patter [0-9, ] and then split the contents with , and take the 0 as Id and 1 as AnotherValueIWant .

Here is a quick code snippet:

public static void main (String[] args)
{
    String sample = "2016-02-06 10:19:36,410 INFO  [[RequestMappingHandlerMapping]]: I am an important log [123, 21] ...{.....}";

    int position = sample.indexOf("INFO");
    System.out.println("TimeStamp: " + sample.substring(0,position-1));

    Pattern MY_PATTERN = Pattern.compile("\\[[0-9, ]+\\]");
    Matcher m = MY_PATTERN.matcher(sample);
    while (m.find()) {
        String str = m.group(0);
        String[] s = str.substring(1,str.length()-2).split(", ");
        System.out.println("Id: " + s[0]);
        System.out.println("AnotherValueIWant: " + s[1]);
    }
}

Output:

TimeStamp: 2016-02-06 10:19:36,410
Id: 123
AnotherValueIWant: 2

You can also do it this way:

if(exampleOfWhatStrLineReturns.contains("important")) {
    String log[]=exampleOfWhatStrLineReturns.split["specific character you want"];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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