Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New Coder
    Join Date
    Oct 2009
    Posts
    51
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Using String "Matches" with Variable

    Hello,

    I'm trying to use matches to find a string within a string, but running into trouble using it with a variable. Concatenating the string doesn't seem to be the answer - what is the correct syntax?

    Code:
    String queryString = request.getQueryString();
    for(String value: mvalues ) {
      if (value.matches("(?i).*" + queryString + ".*")) {
    	out.println(value + " is a match!");  
      }  
    }

  • #2
    New Coder
    Join Date
    Oct 2009
    Posts
    51
    Thanks
    6
    Thanked 0 Times in 0 Posts
    No one uses matches with a variable?

  • #3
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,980
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    I'm not sure I follow you here.
    That above will work fine.
    PHP Code:
    String str "anything /SOMETHING/ done";
    String queryString "/something/";
    String[] str.split(" ");
    for (
    String s a)
    {
        if (
    s.matches("(?i).*" queryString ".*"))
        {
            
    System.out.println(" is a match.");
        }

    Will result in:
    Code:
    /SOMETHING/ is a match
    So since the structure works, it's a problem with the pattern not matching the data.

  • #4
    New Coder
    Join Date
    Oct 2009
    Posts
    51
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Fou-Lu,

    Thanks, you are correct in that it's the pattern; it seems the matches isn't finding the substring anywhere. For example, the 1st works - but teh second doesn't:

    Code:
    String str = "anything /SOMETHING/ done";
    String tstr = "something";
    
    if (tstr.matches("(?i).*/something/.*")) {
            out.println(tstr + " text found.");
        } 
    
    if (tstr.matches("(?i).*anything /SOMETHING/ done.*")) {
        out.println(tstr + " text found.");
    }

    In your example, you used the split to make it work - I can't do so for my purposes because the value I'm searching through won't have any spaces.

    Can you tell what's wrong with the matching regex?

  • #5
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,980
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    I split mine up simply so I'd have an input loop to work with as you had in your original as well.
    What are you matching and pattern you are attempting to match with?


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •