3

Rubyを使用して、次のテキストを正規表現で分割しようとしています

~foo\~\=bar =cheese~monkey

~ または = は、\ でエスケープされていない限り、一致の開始を示します。

だから合ってるはず

~foo\~\=bar

それから

=cheese

それから

~monkey

私は以下がうまくいくと思ったが、うまくいかない。

([~=]([^~=]|\\=|\\~)+)(.*)

使用するより良い正規表現は何ですか?

editより具体的に言うと、上記の正規表現は = と ~ のすべての出現に一致します

作業ソリューションを編集します。これが私が問題を解決するために思いついたものです。Ruby 1.8 には先読みがありますが、後読み機能はありません。それで、少し調べた後、comp.lang.ruby でこの投稿に出くわし、次のように完成させました。

# Iterates through the answer clauses
def split_apart clauses
  reg = Regexp.new('.*?(?:[~=])(?!\\\\)', Regexp::MULTILINE)

  # need to use reverse since Ruby 1.8 has look ahead, but not look behind
  matches =  clauses.reverse.scan(reg).reverse.map {|clause| clause.strip.reverse}

  matches.each do |match|
    yield match
  end
end
4

1 に答える 1

4

この文脈で「頭を取り除く」とはどういう意味ですか?

特定の文字より前のすべてを削除したい場合は、次のようにします。

.*?(?<!\\)=      // anything up to the first "=" that is not preceded by "\"
.*?(?<!\\)~      // same, but for the squiggly "~"
.*?(?<!\\)(?=~)  // same, but excluding the separator itself (if you need that)

「」に置き換え、繰り返し、完了。

文字列にちょうど 3 つの要素 ( "1=2~3") があり、それらすべてを一度に一致させたい場合は、次を使用できます。

^(.*?(?<!\\)(?:=))(.*?(?<!\\)(?:~))(.*)$

matches:  \~foo\~\=bar =cheese~monkey
         |      1      |   2  |  3   |

または、次の正規表現を使用して文字列を分割します。

(?<!\\)[=~]

returns: ['\~foo\~\=bar ', 'cheese', 'monkey']   for "\~foo\~\=bar =cheese~monkey"
returns: ['', 'foo\~\=bar ', 'cheese', 'monkey'] for "~foo\~\=bar =cheese~monkey"
于 2008-12-15T15:30:38.687 に答える