0

Can anyone please suggest me how we can create pattern for below string.

String stringToFind = "Abcdef_ghi_2.0-123_20150424_1642_text.tar.gz";

I have tried with given pattern, but no use. Felt that some where its not satisfying with pattern.

String pattern = "Abcdef_ghi_*_(\\d{8})_(\\d{4})_\\w+";

Thanks In Advance.

4
  • Read a regex tutorial. * doesn't mean what you think it means. Commented Apr 24, 2015 at 11:19
  • String pattern = "Abcdef_ghi_[\\d.-]+_(\\d{8})_(\\d{4})_[.\\w]+"; Commented Apr 24, 2015 at 11:20
  • 1
    You should tell us 1st what's the fixed part and what's the dynamic part expected Commented Apr 24, 2015 at 11:38
  • Here i want to get 20150424 and 1642 from stringToFind variable. That's my requirement.Which I got it from below answers. Commented Apr 24, 2015 at 13:20

2 Answers 2

2

You can use this:

 String pattern = "Abcdef_ghi_.*(\\d{8})_(\\d{4})_\\w+(?:\\.\\w+)*";

Output:

MATCH 1
1.  [19-27] `20150424`
2.  [28-32] `1642`
Sign up to request clarification or add additional context in comments.

3 Comments

stribizhew, its worked as expected.Thanks a lot for your reply.
You are welcome. You should also be more specific, I felt you were using matches method, that is why I extended the pattern till the end. I'd recommend using matcher.find(), but it is really up to you.
@Honey, please accept this answer since it answered your question
1

Instead of _* you need to use _.*?.

You can use:

String pattern = "Abcdef_ghi_.*?_(\\d{8})_(\\d{4})_\\w+.*";

3 Comments

Anubhava, You have to keep \\d instead of \d.Even after correcting this , its not working.Thanks for your reply
How are you matching? Are you calling String#matches() method?
Also I didn't use \d anywhere I have kept it as \\d

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.