简体   繁体   中英

How to take a number from regular expression and pass it to match certain text?

I have the following regular expression [A-Za-z0-9!@#$?]+=(\\d+)<< and I have to match any text after << with length of the number given in the first capturing group ? Can you please help me, appreciate it :)

If you use this RegEx "(\\d+)<<(\\d+)" you can use your capture groups 1 and 2 for your program logic. Here is an example:

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class MainApp {

public static void main(String[] args) {

    String[] searchMe = {"3<<123", "2<<123", "4<<1234", "4<<123"};  
    //indexes 0 and 2 should pass the test 

    String regExPattern = "(\\d+)<<(\\d+)";

    Pattern p = Pattern.compile( regExPattern );

    for(String x : searchMe){
            Matcher m = p.matcher( x );
            boolean b = m.matches();

            if(b)
            {
                int numLen = Integer.parseInt(m.group(1));
                String group2 = m.group(2);
                if(group2.length()  == numLen ){
                    System.out.println(x);
                }
            }



            }
    }

    }

My console prints out:

3<<123
4<<1234

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