简体   繁体   中英

Using regular expressions in Java to do a partial search

ETA at 9:42 pm March 21: Dumb mistake. I made sure the original creation of the object made the name .toUpperCase(). The partial search didn't find the search term because they weren't capitalized. Edited code below. Thank you all for the help.


I'm trying to figure out how to use regular expressions to find out if any pattern of characters matches what's in the object.

For instance, if the name associated with the object was "StackOverflow," I'd like for someone to search "ck" and make the if statement true. So, why is my if statement here not returning true?

ETA: i.getName() returns a string. The program is looping through an ArrayList of objects to find which object has a name that matches the input.

    System.out.println("What name or partial name would you like to filter?");
    String name = input.nextLine();
    int count = 0;
    for (MyObject i: testObject) {
        if (i.getName().matches(".*" + name.toUpperCase() + ".*")) {
            count++;
        }
    }

You need to use toString(). You can not apply matches over an object.

Try that:

System.out.println("What name or partial name would you like to filter?");
String name = input.nextLine();
int count = 0;
for (Object i: testObject) {
    if (i.getName().toString().matches(".*" + name + ".*")) {
        count++;
    }
}

I'm not sure why your code doesn't work, but see this working example, perhaps you have a small mistake somewhere.

Here's a MyObject class that has a name field:

class MyObject {
    private final String name;

    public MyObject(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

and here's the program that find matches:

List<MyObject> myObjects = new ArrayList<MyObject>();
myObjects.add(new MyObject("Stack Overflow"));
myObjects.add(new MyObject("Stack Exchange"));

Scanner input = new Scanner(System.in);
System.out.print("What name or partial name would you like to filter? ");
String pattern = input.nextLine();

int count = 0;
for (MyObject i: myObjects) {
    if (i.getName().matches(".*" + pattern + ".*")) {
        count++;
    }
}

System.out.println("Matches: " + count);

Input:

ck

Output:

Matches: 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM