繁体   English   中英

使用正则表达式和Java在多行字符串中搜索字符串

[英]Search strings in a multi-line string with regex and Java

我对正则表达式的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

我需要DS #18 [1.953125\\1.953125] Pixel Spacing 1.9531251.953125 DS #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”不做任何更改。

谢谢!

如果尝试从输入字符串中提取多个匹配项,则不能使用matchs()方法,因为它将尝试匹配整个输入。 因此,对于多次出现:

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());

埃德森

暂无
暂无

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

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