2015-04-03 56 views
1

我需要提取输入字符串中某个模式后出现的子字符串。我一直在尝试各种组合,但没有得到预期的输出。 输入字符串可以是以下2种形式在特定模式下出现的提取子字符串

1. 88,TRN:2014091900217161 SNDR REF:149IF1007JMO2507 BISCAYNE BLVD STE 
2. 88,TRN:2014091900217161 SNDR REF:149IF1007JMO2507 

我需要编写一个正则表达式,就可以适用于上述2周的变型和提取物,如下“149IF1007JMO2507”部分“SNDR REF:”。 请在下面找到我写的示例程序。

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
public class RegexTester { 
     private static final String input = "88,TRN:2014091900217161 SNDR REF:149IF1007JMO2507 BISCAYNE BLVD STE"; 
     private static Pattern pattern = Pattern.compile(".*SNDR REF:(.*?)(\\s.)*"); 
     private static Matcher matcher = pattern.matcher(input); 
     public static void main (String[] args) { 
       if (matcher.matches()) { 
         System.out.println(matcher.group(1)); 
       } 
     } 
} 

Output:149IF1007JMO2507 BISCAYNE BLVD STE 

我想输出是 '149IF1007JMO2507'

谢谢。

+0

做,如果它不必须是正则表达式我会使用: private static String returnRef(String str){ return str.substring(str.indexOf(“REF”)+ 4,str.indexOf(“REF”)+ 20); } – 2015-04-03 12:30:17

回答

1

您可以使用下面的习惯去找到你的子字符串:

String[] examples = { 
    "88,TRN:2014091900217161 SNDR REF:149IF1007JMO2507 BISCAYNE BLVD STE", 
    "88,TRN:2014091900217161 SNDR REF:149IF1007JMO2507"  
}; 
//       ┌ look-behind for "SNDR REF:" 
//       |    ┌ anything, reluctantly quantified 
//       |    | ┌ lookahead for 
//       |    | | whitespace or end of input 
Pattern p = Pattern.compile("(?<=SNDR\\sREF:).+?(?=\\s|$)"); 
// iterating examples 
for (String s: examples) { 
    Matcher m = p.matcher(s); 
    // iterating single matches (one per example here) 
    while (m.find()) { 
     System.out.printf("Found: %s%n", m.group()); 
    } 
} 

输出

Found: 149IF1007JMO2507 
Found: 149IF1007JMO2507 

注意

我希望你不知道提前这将是"149IF1007JMO2507",因此上下文匹配。

+0

非常感谢梅纳。这是我想要的输出。 – ivish 2015-04-03 12:40:56

+0

@ivish欢迎您! – Mena 2015-04-03 12:43:25

1

你可以使用这个正则表达式:

private static Pattern pattern = Pattern.compile(".*SNDR REF:([^\\s]+).*"); 

这将需要一切“

1

后SNDR REF你可以用的replaceAll

str = str.replaceAll(".*(REF:(\\S+)).*", "$2"); 
相关问题