简体   繁体   English

Java Regex +如何在字符串中找到匹配的模式

[英]Java Regex + How to find a matching pattern within a String

I get a csv file which contains comma separated data. 我得到一个包含逗号分隔数据的csv文件。 Some of this data may contain excel cell number like b1, b2, c1 which represents the MS excel cell numbers 其中一些数据可能包含excel单元格编号,例如b1,b2,c1,代表MS excel单元格编号

Example of CSV data CSV数据示例

b1, 2 3 4 b1, 5 c2 3 d2, 5 4, 2 e1 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. 我需要确定是否有任何csv数据包含a1或c1或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. 我已经使用JAVA正则表达式编写了以下程序。

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. 当数据仅包含b1或c1时,此方法确实起作用,但是当数据之前或之后包含更多字符时,则无法找到b1或c1。

For example 例如

Example 1 works and prints True 示例1可以正常打印

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. 示例2不起作用,并显示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 如何使示例2起作用,以便它可以在包含前后更多字符的字符串中找到b1或c1或a1或a2

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. 在您自己回答的情况下不需要的字符串b22,b&2,cc3等也将true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM