Search code examples
javaregexarraylistjtextfield

Java - String input in textField - search arrayList - include partial matches


Have been at this for a while so I think it's time for some much needed help. I have the following if statement in an action listener('but' - being the Search button that gets clicked for the following to happen).I have an arrayList(used to save data from database) in my class, calling a specific record works perfectly. I am trying to create a search textField(named 'tf' below). I have been able to search only by typing an exact match to what ever is being searched, but I want to be able to use partial matching on any String in tf. Everything that's commented out is different stuff that I have been testing, therefore can be ignored.

The statement: if( srch.getText().equals("You have chosen to search by movie: " ) ... this is used to make sure that the person is searching only when the panel includes this title, as there is a genre search as well on the same panel. Only the title changes.

        if(source.equals(but)){
         //String b = a.get(0).get(1);
         String result = tf.getText();
         Pattern pat = Pattern.compile("[a-z]+");
         Matcher m = pat.matcher(result);
         //boolean bool = m.matches();
         int i = 0;
         //al.contains(result) && pat.matcher(a.get(i).get()).matches())
         // && z.contains(result)
       if( srch.getText().equals("You have chosen to search by movie: " )){ 
           for (ArrayList<String> al : a){  
                if (pat.m(a.get(i).get(0)).matches()){  
                  System.out.println(a.get(i).get(0)); //movie name
                  System.out.println(a.get(i).get(1)); //movie desc
         }
          i++;
          }
          //ta.setText(b);
        }
        else{
            ta.setText("Please try searching by movie");
        }
      }

In summary, everything works fine. I just need a regex code to find partial matches as well and a way to add that into my loops. I've added as little code as possible as not to waste anyone's time, so please let me know if any other is needed.Many thanks in advance. Eventually any full or partial matches will display the movie name and description.


Solution

  • I think there is no need of regex.

    String.contains(String chars) returns true if the source string have any occurrence of the argument string.

    For example:

    String str = "ABCDEFG";
    
    if(str.contains("CD")){
         System.out.println("Present");
    }