1

I would like to use a regex to find the word between _ and . in the filename.

Example: If the filename reads ---- abc_resend.zip

I would like my pattern to return "resend".

I tried using the following pattern: "\_([a-z]*)\." Result: _resend.

Tried the following pattern to exclude: "(?:\\_)([a-z]*)(?:\\.) and am still getting the same result: _resend.

What am I doing wrong? Please help.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • 1
    you need to use the group 1's value – Pavneet_Singh Jun 15 '17 at 17:55
  • "I tried using the pattern" - language, API used to get the result? – Aseem Bansal Jun 15 '17 at 17:55
  • Using Javascript /_([a-z]*)\./.exec('abc_resend.zip'), I got ["_resend.", "resend"]. The latest capture is the one you look for. – roland Jun 15 '17 at 17:57
  • Unfortunately I am using a custom (primitive) API which only allows me to work with the pattern to return the group I desire. Given that, if I want to break the filename into groups and use exclusions (?: ) shouldn't that work ? – user3411153 Jun 15 '17 at 18:23

3 Answers3

1

The issue is that you are looking for a regular expression which matches this certain pattern. I am not sure which language you are writing in, but you want to get this result and then use some kind of strip method in order to remove those two characters from the outside. You're going to get this result because you're looking for it: the next step is since you always know what you're gonna get, to use a strip method to remove the rest. If you let me know which language you are using, I can help you track down the specific syntax.

JoshKopen
  • 940
  • 1
  • 8
  • 22
  • Java. You are correct. I can substring the result but was wondering if I could avoid running two functions and achieve the result with just the regex pattern. – user3411153 Jun 15 '17 at 18:07
1

. is a special character in RegEx so you need to escape it with a \ if you want to match a . character. Try this: _([a-z]*)\.

Lews Therin
  • 3,707
  • 2
  • 27
  • 53
1

You can solve your problem using pattern with this regex _(\w+)\. :

String str = "abc_resend.zip";
Pattern pattern = Pattern.compile("_(\\w+)\\.");
Matcher matcher = pattern.matcher(str);

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

Output

resend
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • So, the exact same as the comment I [linked in my answer](https://stackoverflow.com/a/3010780/4416750)? Nice. – Lews Therin Jun 15 '17 at 18:47
  • @LewsTherin believe me, i see your link after i post my answer, but it is different not the same 100%, ii hoped you get this 15 point really – Youcef LAIDANI Jun 15 '17 at 18:55