0

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

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
ErEcTuS
  • 777
  • 1
  • 14
  • 33
  • 5
    So what do you want to extract in your example, `014qsqs`? What did you try so far? And does it have to be a regex or would splitting the filename at dashes be ok as well? – Thomas May 09 '17 at 11:07
  • 3
    Why do you specifically want to use a regex for this? Regular expressions are not a golden hammer for any task that has to do with strings, and a simple `indexOf` and `substring` will do the job here. – Jesper May 09 '17 at 11:08
  • 1
    http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java – user2173372 May 09 '17 at 11:10
  • No actually I need everything before the second dash. In this case, I need to have as a result "fileName-014qsqs" – ErEcTuS May 09 '17 at 11:32

3 Answers3

2

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.

Daniel Centore
  • 3,220
  • 1
  • 18
  • 39
0

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.

user1708042
  • 1,740
  • 17
  • 20
0

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

J.Fernandes
  • 87
  • 2
  • 10