0

次のファイルの内容があり、各行の先頭にある連続する文字ブロック (具体的には「>」) の正規表現を照合し、一致するテキストのブロックを削除しようとしています。

-- file.txt (Before regx match and replace) -- 
keep this

> remove this
>
> remove this too
-- EOF -- 


-- file.txt (After regex mach and replace) -- 
keep this

-- EOF -- 

これを複数行に一致させようとしています(つまり、「>」で始まる行を削除します)。これは正しいですか、それとも最善のアプローチですか? 以下は動作していないようです。

    // String text = <file contents from above...the Before contents>
    Pattern PATTERN = 
      Pattern.compile("^>(.*)$", Pattern.MULTILINE);
    Matcher m = PATTERN.matcher(text);
    if (m.find()) {
       // Matches each line starting with > and deletes (replaces with "") the line
       text = m.replaceAll("");  

    }
4

2 に答える 2

2

述べたように、置換に@Peter Alfvin改行を含める必要があります。\n

text = text.replaceAll("(?m)^>[^>]*?\n", "");

正規表現:

(?m)           set flags for this block (with ^ and $ matching start and end of line)
^              the beginning of a "line"
>              '>'
 [^>]*?        any character except: '>' (0 or more times)
               (matching the least amount possible))
 \n            '\n' (newline)

(?m)修飾子 (複数行) により^、 andが各行の$開始/終了に一致します。

見るworking demo

于 2013-11-04T05:50:04.197 に答える
2

これらの行を完全に削除するには、行末 ( \n) までではなく、行末 ( ) まで一致させる必要があります。$

于 2013-11-04T01:57:28.017 に答える