【问题标题】:Regular Expression to find a word that starts with 'JD' fixed word length, in java正则表达式在java中查找以'JD'固定字长开头的单词
【发布时间】:2015-04-02 07:05:55
【问题描述】:

我不是正则表达式专家,在以下问题中需要您的帮助。

我需要从包含以 JD 开头的字母的字符串中找到一个单词,该单词的长度已知,即 20。 对于这种情况,假设 String 是 "Your shipment 6016499344 was delivered at ABC JD014600001678885621 Piece ID"

【问题讨论】:

    标签: java regex regex-negation


    【解决方案1】:

    您可以尝试以下带有模式和匹配器类的正则表达式。

    "\\bJD\\w{18}\\b"
    

    \b 匹配单词字符和非单词字符(反之亦然

    示例:

    String s =  "Your shipment 6016499344 was delivered at ABC JD014600001678885621 Piece ID";
    Matcher m = Pattern.compile("\\bJD\\w{18}\\b").matcher(s);
    while(m.find())
    {
        System.out.println(m.group());
    }
    

    String s =  "Your shipment 6016499344 was delivered at ABC JD014600001678885621 Piece ID";
    Matcher m = Pattern.compile("(?<!\\S)JD[A-Za-z\\d]{18}(?!\\S)").matcher(s);
    while(m.find())
    {
        System.out.println(m.group());
    }
    

    输出:

    JD014600001678885621
    

    【讨论】:

    • 接受您最喜欢的答案。
    【解决方案2】:

    您可以使用简单的\bJD[a-zA-Z0-9]{18}\b 正则表达式。

     String rx = "\\bJD[a-zA-Z0-9]{18}\\b";
    

    解释:

    • \b - 边界
    • JD - 第一个条件 - 这些字母必须匹配
    • [a-zA-Z0-9]{18} - 从 a 到 z 的任何拉丁字符(不区分大小写)或从 0 到 9 的数字
    • \b - 边界

    您需要使用单词边界来匹配以“JD”开头的文本部分。

    如果你在一个文本中有多个 JD 字符串,你可以像这样匹配它们(见sample program here):

    public static void main(String []args){
    
        String str = "Your shipment 6016499344 was delivered at ABC JD014600001678885621 Piece ID\nYour shipment 918947344 was delivered at ABC JD024900901978985929 Piece ID";
        String rx = "(?<=^|\\b)JD[a-zA-Z0-9]{18}";
        Pattern ptrn = Pattern.compile(rx);
        Matcher m = ptrn.matcher(str);
        while (m.find()) {
            System.out.println(m.group(0));
        }
     }
    

    【讨论】:

    • \b 也涵盖了^。无需再次指定 :)
    • @vks:我更喜欢玩得最安全 :) 但你又是对的。
    • @TarunChaudhary:很高兴为您提供帮助。我还添加了正则表达式解释。
    【解决方案3】:

    你可以使用:

    public static void main(String[] args) {
        String s = "Your shipment 6016499344 was delivered at ABC JD014600001678885621 Piece ID";
        System.out.println(s.replaceAll(".*(JD\\d{18}).*", "$1"));
    }
    

    O/P:

    JD014600001678885621
    

    【讨论】:

    • 这里“$1”是什么意思,即你使用它的原因。
    • @TarunChaudhary - 这意味着第一个选定的组。即第一个 () 中的值
    【解决方案4】:

    使用Matcher 对象并使用Matcher.find() 在输入字符串中查找匹配项:

        Pattern p = Pattern.compile("\\bJD\\d{18}\\b");
        Matcher m = p.matcher("Your shipment 6016499344 was delivered at ABC JD014600001678885621 Piece ID");
        m.find();
        System.out.println(m.group());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-02
      • 2017-07-09
      • 1970-01-01
      相关资源
      最近更新 更多