1

So I am trying to get the data from a line that looks like this:

GET /something HTTP/1.1 

Now, I here is my code with the regex:

 final ServerSocket server = new ServerSocket(8081);
    System.out.println("Listening on port 8081...");
    while (true) {
        final Socket clientSocket = server.accept();

        InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
        BufferedReader reader = new BufferedReader(isr);

        String line = reader.readLine();

        Pattern pattern = Pattern.compile("GET \\/(.*?) HTTP");
        Matcher m = pattern.matcher(line);

        System.out.println(m.find());

the "/something" is what I need to get, and it will always be something different in actual usage. The code always prints out "true", instead of what should be in the string. What am I doing wrong?

2

3 Answers 3

4

You have to use the Group method to get the mathing value.

find only tells you if the string mathches:

Pattern pattern = Pattern.compile("GET \\/(.*?) HTTP");
Matcher m = pattern.matcher(line);
if (m.find())
    System.out.println(m.group(0));
Sign up to request clarification or add additional context in comments.

Comments

2

You need to go 1 step further by using the group API to get the captured set values from your regular expression.


Note: group does not starts from position 0. The first element is just your original input value. You need to start from position 1.

Example:

private void doIt3() {
    String line = "GET /something HTTP/1.1 ";
    Pattern pattern = Pattern.compile("GET \\/(.*?) HTTP");
    Matcher m = pattern.matcher(line);

    if (m.find()) {
        System.out.println("Found value => " + m.group(1));
    }
}

Output:

Found value => something

Comments

2

find method in Matcher class is expected to return a boolean value not matched string.

You can see documentation as follows:

public boolean find(): Attempts to find the next subsequence of the input sequence that matches the pattern.

You can use following code snippet to find all matching patterns.

Matcher m = Pattern.compile("GET \\/(.*?) HTTP").matcher(line);

while (m.find()) {
    System.out.println(m.group());
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.