Hi I have a list of Strings..

List list = new ArrayList();
list.add("Test");
list.add("Test Test");
list.add("Test Second");

I want to search string like "Te*"..

I used the following code for searching

queryString = "Te*";
    queryString = queryString.replaceAll("\\*", "\\\\w*");
    for (String str : values) {
            if (str.matches(queryStr) || str.contains(queryStr))
                list.add(str);
    }

This piece of code returning only 'Test'.. but not "Test Test"..

If element having spaces , then this code is not working

有帮助吗?

解决方案 3

I am by no means a regex expert. But not replacing the * at all, and adding a .* at the end did it for me

List<String> list = new ArrayList<String>();
        list.add("Test");
        list.add("Test Test");
        list.add("Test Second");
        String queryString = "Te*s";
//      queryString = queryString.replaceAll("\\*", "\\.\\*");
        queryString = queryString.concat(".*");
        for (String str : list) {
                if (str.matches(queryString))
                    System.out.println(str);
        }

其他提示

That's because you're replacing your * to \w* which means find "word characters" until you can, as described here try replacing it .* that should do the trick and you could also get rid of those ugly escapes :) Also you could use java8 stream api to make it look nicer like this:

List<String> list = values.stream().filter( s -> s.matches(queryStr)).collect(Collectors.toList());

Following code works:

String queryStr = "Te.*";
for (String str : list) {
    if (str.matches(queryStr))
        values.add(str);
}
System.out.println(values);

The first issue was that matches() matches complete string, so you had to update regexp. \w will match word and if there is space than it is another word. This in conjuction with matches() caused that it will never work. I modified the regexp so it will match all strings starting with Te, because .* will match everything else.

There was another bug, that you were trying to iterate over str list and then add found element into the same list. Java would throw ConcurrentModificationException.

You have a few issues

  1. matches only returns true for a full-string match, not a sub-string match
  2. \w only matches word characters not spaces.
  3. contains finds literal sub-string matches, not regular expressions.

Your solution is either:

  1. Replace your query string with one that actually matches what you want to match - probably you want to change it to use .replaceAll("\\*", ".*")
  2. Use Pattern.find instead of String.match

Try with Pattern.quote.

yourString.replaceAll(Pattern.quote("Te"),"");

Here it is replacing all "Te" by "";

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top