简体   繁体   中英

Java Regex + How to find a matching pattern within a String

I get a csv file which contains comma separated data. Some of this data may contain excel cell number like b1, b2, c1 which represents the MS excel cell numbers

Example of CSV data

b1, 2 3 4 b1, 5 c2 3 d2, 5 4, 2 e1

I need to identify if any of the csv data contains data like a1, or c1, or b1.

ie I need to find if the data contains a charachter followed by a number.

I have written the below program using JAVA regex.

while this does work when the data only contains b1 or c1, but it fails to find b1 or c1 when the data contains more charachters before or after it.

For example

Example 1 works and prints True

package com.test;

public class PatternTest {

    public static void main(String[] args) {
        String pattern = "(([A-Za-z].*[0-9]))";

        String data = "b2";
        if(data.matches(pattern)){
            System.out.println("true");
        }else{
            System.out.println("false");
        }

    }

}

Example 2 doesnt work and prints false. How can I make example 2 work so that it can find a b1 or c1 or a1 or a2 from within a String that contains more charachters before and after

package com.test;

public class PatternTest {

    public static void main(String[] args) {
        String pattern = "(([A-Za-z].*[0-9]))";

        String data = "1 b2 3 4 ";
        if(data.matches(pattern)){
            System.out.println("true");
        }else{
            System.out.println("false");
        }

    }

}

please ignore. I found the solution as shown below

package com.test;

public class PatternTest {

    public static void main(String[] args) {
        String pattern = "((.*[A-Za-z].*[0-9].*))";

        String data = "c2 3 c2 *";
        if(data.matches(pattern)){
            System.out.println("true");
        }else{
            System.out.println("false");
        }



    }

}

You can do it like this:

String str = "b1, 2 3 4 b1, 5 c2 3 d2, 5 4, 2 e1";
if (str.matches(".*\\p{Alpha}\\d.*")) {
    System.out.println(true);
} else {
    System.out.println(false);
}
// Result is true for current str

In your case which you answered by yourself it will be true also for these strings b22, b&2, cc3 etc which you do not want.

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