'In java Regex, How can I get a certain part of a fileName

I have a String which is basically a file name. I need to retrieve a certain part of the file name. It is the value before second - (dash). Filenames will be in format example:

fileName-014qsqs-xxxxyyyzzz.txt

I need to get as a result:

fileName-014qsqs

How can I use regex to it?

Thanks



Solution 1:[1]

When trying to figure this out, it can be helpful to use a regex tester (e.g. http://www.regexplanet.com/advanced/java/index.html)

The regex (.*?-.*?)-.* matches what you are looking for.

.*: Any character any number of times

?: Makes it non-greedy, so it only does as few as possible to match

-: Literal dash

(): The parentheses make it a group so it can be extracted.

The entire program looks like this:

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

public class Main
{
    public static void main(String atrgs[])
    {
        String line = "fileName-014qsqs-xxxxyyyzzz.txt";
        Pattern pattern = Pattern.compile("(.*?-.*?)-.*");
        Matcher matcher = pattern.matcher(line);
        while (matcher.find()) {
            System.out.println(matcher.group(1));
        }
    }
}

And has the output fileName-014qsqs.

Solution 2:[2]

You can use this regular expression:

"([^-]*-[^-]*)-.*"

Explanation: any character but "-" is expressed as "[^-]" hence the

([^-]*-[^-]*)

captures a sequence of non-"-" characters separated by a single "-", next a second "-" followed by any further text.

Solution 3:[3]

Hi i probably do a while and when find the 2 "-" stop.Sry can't comment

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 user1708042
Solution 3