Possible Duplicate:
Search for a regexp in a java arraylist
Is there a way to access items stored in a List using regular expressions?
Take the following code as an example:
String jpg = "page1.jpg";
String jpeg = "page-2.jpeg";
String png = "page-003.png";
ArrayList<String> images = new ArrayList<String>();
images.add( jpg );
images.add( jpeg );
images.add( png );
Pattern regex = Pattern.compile( "\\D{4,5}0*1.\\w{3,4}" );
int index = images.indexOf( regex );
if( index != -1 )
System.out.println( "Did find the string" );
else
System.out.println( "Didn't find the string" );
The code above does not work in finding the string page1.jpg and instead returns -1.
Is there a way that this can be achieved without iterating through the List and checking whether a string matches a regex?
Not really. Short of subclassing
ArrayListor using scala, groovy, etc, there isn’t.indexOfuses theequalsmethod, so you’re stuck.If you’re willing to use dark arts, you could create a custom class with a
equalsmethod that uses the regex.But I’d just iterate. It’s cleaner. You’re co-workers and yourself in 6-months time will appreciate it.