-1

I have a regex that finds a certain pattern. This works when the text is isolated. However I want this to work while it's being surrounded by other text and somehow extract it from there. Here's the pattern that I came up with. An example would be if 9708/32/M/J/15 is the text, it would find it. But if it's awfawf9708/32/M/J/15awfafwaf it can't find it.

Pattern pattern = Pattern.compile("^\\d{4}/\\d{2}/\\w/\\w/\\d{2}$");

How do I modify this to make it work in both scenarios?

patrick.elmquist
  • 1,957
  • 2
  • 18
  • 30
HudZah
  • 45
  • 7

1 Answers1

0

The ^ asserts beginning of string. $ asserts end of string. Parenthesis are used to capture what's matched inside them. Both of these will work:

(\d{4}/\d{2}/\w/\w/\d{2})
^.*(\d{4}/\d{2}/\w/\w/\d{2}).*$

I'm not sure why you were escaping your backslashes. You may need to escape your forward slashes if forward slash is used as a delimiter in your program. I prefer to use ~ as delimiter as it is a rare character.

Pan
  • 321
  • 1
  • 7
  • I get an error of Illegal escape character on android studio. Espacing the backslashes fixes the problem – HudZah Jan 11 '20 at 15:56