#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    10
    Rep Power
    0

    What is correct regex for String.matches?


    Hello all,

    I want to test whether a string matches a certain regular expression, but I don't think I'm entering the regular expression correctly. In plain English, I want to test whether the expression "(RSP_dddd & RSP_dddd) | (RSP_dddd & RSP_dddd)," where d is a digit from 0-9, is in the string "genes."

    Take a look:
    Code:
    import java.io.*;
    
    import java.util.Arrays;
    
    import java.util.ArrayList;
    
    import java.util.List;
    
    import java.util.regex.*;
    
    
    
    public class test{
    
    
    
     public static void main(String[] arg) throws Exception {
    
    
    
    
    String genes = "(RSP_1146 & RSP_1149) | (RSP_1146 & RSP_0189) RSP_0147 | RSP_2319 | RSP_0375 | RSP_0377 | RSP_1568 RSP_0723 (RSP_3526 & RSP_1249) | (RSP_8886 & RSP_2219)";
    
    		
    if(genes.matches("("+"RSP_\\d+"+"&"+"RSP_\\d+"+")|("+"RSP_\\d+"+"&"+"RSP_\\d+"+")"))
    
    {		
    System.out.println("yes");
    
    }	
    
    
    
    
    
    
     }
    
    }
    The output is empty, but it should be "yes" on line 1 then "yes" on line 2, since there are two instances of "(RSP_dddd & RSP_dddd) | (RSP_dddd & RSP_dddd)." Any ideas on how to rewrite this regex?

    Thanks a lot,

    k
  2. #2
  3. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Feb 2004
    Location
    Mobile, Alabama
    Posts
    4,023
    Rep Power
    1285
    Remember that in regular expressions, ( ) and | have special meanings so you need to escape them. Also note there is white space around & and after the )

IMN logo majestic logo threadwatch logo seochat tools logo