4

問題

次のような行でいっぱいのファイルがあります

convert.these.dots.to.forward.slashes/but.leave.these.alone/i.mean.it

取得したものを検索して置換したい

convert/these/dots/to/forward/slashes/but.leave.these.alone/i.mean.it

。最初のスラッシュまで / に変換されます

質問

問題を解決するために正規表現の検索と置換を作成するにはどうすればよいですか?

試みられた解決策

perlで後読みしてみましたが、可変長の後読みが実装されていません

$ echo "convert.these.dots.to.forward.slashes/but.leave.these.alone/i.mean.it" | perl -pe 's/(?<=[^\/]*)\./\//g'
Variable length lookbehind not implemented in regex m/(?<=[^/]*)\./ at -e line 1.

回避策

可変長の先読みが実装されているため、この汚いトリックを使用できます

$ echo "convert.these.dots.to.forward.slashes/but.leave.these.alone/i.mean.it" | rev | perl -pe 's/\.(?=[^\/]*$)/\//g' | rev
convert/these/dots/to/forward/slashes/but.leave.these.alone/i.mean.it

この問題に対するより直接的な解決策はありますか?

4

2 に答える 2

5
s/\G([^\/.]*)\./\1\//g

\G前の一致の最後のポイントに一致するアサーションです。これにより、連続する各一致が最後の一致の直後に続くことが保証されます。

一致:

\G          # start matching where the last match ended
([^\/.]*)   # capture until you encounter a "/" or a "."
\.          # the dot

置き換え:

\1     # that interstitial text you captured
\/     # a slash

使用法:

echo "convert.these.dots.to.forward.slashes/but.leave.these.alone/i.mean.it" | perl -pe 's/\G([^\/.]*)\./\1\//g'

# yields: convert/these/dots/to/forward/slashes/but.leave.these.alone/i.mean.it

あるいは、あなたが純粋主義者で、キャプチャされたサブパターンを追加したくない場合 — 回避する方が効率的かもしれませんが、私には確信が持てません — を使用\Kして、「実際の」一致を.に置き換えるだけ/です。\K基本的に、その時点までに一致したものを「忘れる」ため、最終的に返される最終一致は\K.

s/\G[^\/.]*\K\./\//g

一致:

\G        # start matching where the last match ended
[^\/.]*   # consume chars until you encounter a "/" or a "."
\K        # "forget" what has been consumed so far
\.        # the dot

したがって、置換に一致するテキスト全体は単純に " ." です。

置き換え:

\/      # a slash

結果は同じです。

于 2013-04-19T00:58:27.697 に答える
2

左辺値として使用substrして、その上で置換を実行できます。または、以下で行ったように、音訳。

$ perl -pe 'substr($_,0,index($_,"/")) =~ tr#.#/#'
convert.these.dots.to.forward.slashes/but.leave.these.alone/i.mean.it
convert/these/dots/to/forward/slashes/but.leave.these.alone/i.mean.it

これにより、スラッシュの最初のインスタンスが検出され、文字列のその前の部分が抽出され、その部分の音訳が実行されます。

于 2013-04-19T01:02:51.693 に答える