Use Java regex to find matching string in middle of a string

java, regex, string

Solution

Try this:

if (!arcvalFileFormBean.getTxtFileReview().matches(
               ".*?v[0-9]{4}_[0-9]{2}_[0-9]{2}_[0-9]{4}_[0-9]{4}.*"))

`String#matches` attempts to match complete input therefore `.*?` before your version regex and `.*` after this will make sure that this pattern is matched anywhere in the input.

Problem

I need to validate a file input to make sure it has the correct versioning on it. This, for example is the input file: `W:\\folder\\test_v2301_01_29_2014_1420.pfd` I have built a regex in Java to find the versioning string I am looking for to validate the file. RegEx: `v[0-9]{4}_[0-9]{2}_[0-9]{2}_[0-9]{4}_[0-9]{4}` However, it fails because the regex is looking at the start of the file. Called: `if (!arcvalFileFormBean.getTxtFileReview().matches("v[0-9]{4}_[0-9]{2}_[0-9]{2}_[0-9]{4}_[0-9]{4}"))` What is the best way to search for the string not knowing how far from the beginning it will be?

Original source