使用regex和Java搜索多行字符串中的字符串

时间:2011-01-28 15:00:08

标签: java regex

我对regex的Java语法感到非常不安...这是我的(多行)字符串:

2054:(0020,0032) DS #36 [-249.28170196281\-249.28170196281\0] Image Position (
2098:(0020,0037) DS #12 [1\0\0\0\1\0] Image Orientation (Patient)
2118:(0020,0052) UI #52 [1.3.12.2.11...5.2.30.25....2.20....0.0.0]
2178:(0020,1040) LO #0 [] Position Reference Indicator
2222:(0028,0004) CS #12 [MONOCHROME2] Photometric Interpretation
2242:(0028,0010) US #2 [256] Rows
2252:(0028,0011) US #2 [256] Columns
2262:(0028,0030) DS #18 [1.953125\1.953125] Pixel Spacing
2288:(0028,0100) US #2 [16] Bits Allocated
2298:(0028,0101) US #2 [12] Bits Stored
2352:(0028,1055) LO #6 [Algo1] Window Center & Width Explanation

我需要来自1.953125

1.953125DS #18 [1.953125\1.953125] Pixel Spacing

我试过了:

Pattern p = Pattern.compile("DS #18 \\[([0-9\\.]*)\\\\([0-9\\.]*)\\] Pixel Spacing"); // os is my string above
System.out.println(m.matches()); // false =(

但没有成功。任何的想法? “Pattern.MULTILINE”不会改变任何东西。

谢谢!

1 个答案:

答案 0 :(得分:4)

如果您尝试从输入字符串中提取多个匹配项,则不能使用matches()方法,因为它会尝试匹配整个输入。所以多次出现:

Pattern p = Pattern.compile("DS \\#18 \\[([0-9\\.]*)\\\\([0-9\\.]*)\\] Pixel Spacing",
                            Pattern.MULTILINE|Pattern.DOTALL); 
Matcher m = p.matcher( input );
while( m.find() ) {
    System.out.println("[ "+m.group( 1 )+", "+m.group( 2 )+" ]");
}

如果您想要一次出现,那么您需要在模式的开头和结尾添加。*:

Pattern p = Pattern.compile(".*DS \\#18 \\[([0-9\\.]*)\\\\([0-9\\.]*)\\] Pixel Spacing.*",
                            Pattern.MULTILINE|Pattern.DOTALL); 
System.out.println(m.matches());

埃德森