开发者

Using regex to access items in a List [duplicate]

开发者 https://www.devze.com 2023-03-23 15:38 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Search for a regexp in a java arraylist
This question already has answers here: Closed 11 years ago.

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 ArrayList or using scala, groovy, etc, there isn't. indexOf uses the equals method, so you're stuck.

If you're willing to use dark arts, you could create a custom class with a equals method that uses the regex.

int index = images.indexOf(new Object() {
    public boolean equals(Object obj) {
        return regex.matches(obj.toString());
    }
});

But I'd just iterate. It's cleaner. You're co-workers and yourself in 6-months time will appreciate it.


The code above does not work in finding the string page1.jpg and instead returns -1.

It's not supposed to work that way. The Object parameter for ArrayList.indexOf is supposed to be an object you expect to be in the collection.

What you could do is extend ArrayList and overload indexOf to support Patterns.

0

精彩评论

暂无评论...
验证码 换一张
取 消