1

私は Java を使用しており、2 つの異なるシナリオに適合する 2 つの正規表現を作成したいと考えています。

1:

STARTText blah, blah
\    next line with more text, but the leading backslash
\    next line with more text, but the leading backslash
\    next line with more text, but the leading backslash

最初の行がバックスラッシュで始まらなくなるまで。

2:

Now you will see the following links for the items:
1111 leading 4 digits and then some text
2565 leading 4 digits and then some text
8978 leading 4 digits and then some text

このブロックは、たとえば 8978 の後に空の行が追加されて終了します。ただし、さらに、開始桁のブロックが 10 回繰り返されて終了することもわかっています。

したがって、個々の行をフィルタリングすることは何とか可能ですが、間に複数の改行を入れてそれを行うにはどうすればよいでしょうか? そして、いつ/どのように終了するのか本当にわからない最初のブロックでも。また、バックスラッシュの検索。したがって、私のアプローチは、1 つだけの閉じた式を持つことです。これは、replaceAll() にも使用できます。

4

4 に答える 4

1

最初の正規表現:

Pattern regex = Pattern.compile(
    "^          # Start of line\n" +
    "STARTText  # Match this text\n" +
    ".*\\r?\\n  # Match whatever follows on the line plus (CR)LF\n" +
    "(?:        # Match...\n" +
    " ^\\\\     # Start of line, then a backslash\n" +
    " .*\\r?\\n # Match whatever follows on the line plus (CR)LF\n" +
    ")*         # Repeat as needed", 
    Pattern.MULTILINE | Pattern.COMMENTS);

2 番目の正規表現:

Pattern regex = Pattern.compile(
    "(?:        # Match...\n" +
    " ^         # Start of line\n" +
    " \\d{4}\\b # Match exactly four digits\n" +
    " .*\\r?\\n # Match whatever follows on the line plus (CR)LF\n" +
    ")+         # Repeat as needed (at least once)", 
    Pattern.MULTILINE | Pattern.COMMENTS);
于 2013-05-31T12:51:47.873 に答える
1

正規表現 1:

/^STARTText.*?(\r?\n)(?:^\\.*?\1)+/m

ライブデモ: http://www.rubular.com/r/G35kIn3hQ4

正規表現 2:

/^.*?(\r?\n)(?:^\d{4}\s.*?\1)+/m

ライブデモ: http://www.rubular.com/r/TxFbBP1jLJ

編集:

Java デモ 1: http://ideone.com/BPNrm6

Java の正規表現 1:

(?m)^STARTText.*?(\\r?\\n)(?:^\\\\.*?\\1)+

Java デモ 2: http://ideone.com/TQB8Gs

Java の正規表現 2:

(?m)^.*?(\\r?\\n)(?:^\\d{4}\\s.*?\\1)+
于 2013-05-31T12:57:00.193 に答える