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
.