简体   繁体   English

正则表达式-替换所有出现的奇数/偶数

[英]Regex - replace every odd/even occurrence

OK, guys, the task is to replace every odd occurrence of a pattern A with pattern B and every even occurrence with pattern C. I gave up on this and wrote a python script for the task but I was wondering if it can be handled with regular expression replacement (via eg. sed or vi) 好的,伙计们,任务是用模式B替换模式A的每个奇数事件,用模式C替换每个偶数的事件。我放弃了这一点,并为该任务编写了python脚本,但是我想知道是否可以使用正则表达式替换(例如sed或vi)

If you need to know what purpose this is for, it is to reformat a long text with double quotes to the LaTeX style (`` opens, '' closes). 如果您需要知道这是什么目的,那就是将长文本重新格式化为带LaTeX样式的双引号(``打开,''关闭)。

Most straightforwardly by reading the file fully into the pattern space before working on it -- since it's a LaTeX source file, I assume that it fits into memory comfortably. 最直接的方法是在处理文件之前将其完全读取到模式空间中-由于它是LaTeX源文件,因此我认为它可以舒适地放入内存中。 You might use 你可能会用

sed ':a $!{ N; ba }; s/"\([^"]*\)"/``\1'"''"'/g' filename.tex

Shell quoting of the '' (LaTeX closing quotes) makes this look more confusing than it is. Shell引号'' (LaTeX的右引号)比实际情况更令人困惑。 What sed sees is sed看到的是

:a $!{ N; ba }          # read the whole file into the pattern space
s/"\([^"]*\)"/``\1''/g  # replace all quoted strings with LaTeX-quoted strings

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM