【问题标题】:How to match a given regex pattern to get a substring from a String如何匹配给定的正则表达式模式以从字符串中获取子字符串
【发布时间】:2018-10-30 05:23:12
【问题描述】:

我有一个字符串表示 ex-“Abc Xyz Def OSSV-1810-017466-AB01 Def Utv” 如何编写一个正则表达式来计算“OSSV-1810-017466-AB01”等格式并仅从任何给定字符串中提取它?

尝试了什么:

public class RegexTest { 
    public static void main(String[] args) { 
        String str = "Abc Xyz Def OSSV-1810-017466-AB01 Def Utv"; 
        Pattern pattern = Pattern.compile("[a-zA-Z\\-\\0-9\\-\\0-9\\-\\^A-Za-z0-9]"); 
        Matcher matcher = pattern.matcher(str); 
        System.out.println(matcher.toString()); 
        if(matcher.find()){ 
            System.out.println("found" + matcher.group(1)); 
        } 
        else{ 
            System.out.println("not found"); 
        } 
    } 
}   

【问题讨论】:

  • 请发布您尝试过的代码。网上有很多例子可以做到这一点。
  • 还有什么逻辑会给出这个结果?
  • 嗨,Kartik 我无法为该子字符串获得正确的正则表达式模式
  • 欢迎来到 SO,请四处看看,看看如何在这个社区提出适当的问题。
  • 也许这对你有用:String theStuffINeed = "Abc Xyz Def OSSV-1810-017466-AB01 Def Utv".split("\\s+")[3];

标签: java regex string


【解决方案1】:

您可以使用此模式[A-Z]{4}-\\d{4}-\\d{6}-[A-Z]{2}\\d{2}

还将matcher.group(1) 更改为matcher.group(0)

【讨论】:

    【解决方案2】:
    public static void main(String[] args) {
        String input="Abc Xyz Def OSSV-1810-017466-AB01 Def Utv";
    
        String regEx="([a-zA-Z ]*)((?:[A-Z]{4}-)(?:[0-9]{4}-)(?:[0-9]{6}-)(?:[A-Z0-9]{4}))([a-zA-Z ]*)";
        Matcher matcher = Pattern.compile(regEx).matcher(input);            
    
        if(matcher.matches()) {         
            System.out.println(matcher.group(2));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 2023-02-04
      • 2017-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      相关资源
      最近更新 更多