簡體   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