user2205591
user2205591

Reputation: 23

Regex not working as expected in Java

I'm using regex that works in RegexBuddy but doesn't work in Java.

This is my regex: (?<=(files)\\s)(.*)

This is the string I'm testing it on: "–files /root1/file1.dat;/root/file2.txt"

In RegexBuddy it's returning: "/root1/file1.dat;/root/file2.txt" but in Java it returns just the literal word files.

Why isn't this working?

Upvotes: 2

Views: 121

Answers (2)

Daniel Walton
Daniel Walton

Reputation: 228

Strange, I'm running this and i see no difference if i put the brackets around files or not. The brackets inside the look-behind don't make a difference.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class regex
{
    public static void main(String[] args)
    {

        String s = "-files /root1/file1.dat;/root/file2.txt";
        Pattern p = Pattern.compile("(?<=-(files)\\s)(.*)");
        Matcher m = p.matcher(s);
        System.out.println(m.find());
        System.out.println(m.group());
    }
}

Note that if you are trying to parse command line parameters like this then it is probably a bad idea as you will run into problems (potentially) with this overlapping on other parameters. What about the case such as " -docs freds-files -files blah.txt" ?

Upvotes: 0

Kent
Kent

Reputation: 195059

try this regex:

(?<=files\\s)(.*)

EDIT add explanation

I guess you were taking group(1)

your regex: (?<=(files)\\s)(.*) has three match groups:

group 0:/root1/file1.dat;/root/file2.txt
group 1:files
group 2:/root1/file1.dat;/root/file2.txt

mine: (?<=files\\s)(.*) has two:

group 0:/root1/file1.dat;/root/file2.txt
group 1:/root1/file1.dat;/root/file2.txt

the group in look-behind is actually not necessary, and your (.*) became group(2) if you want to get `/root1.....$', you don't have to group,

(?<=files\\s).*

will do the job.

anyway, if you want to stick to your regex, take group(2)

I hope it is clear explained.

Upvotes: 3

Related Questions