我想使用C#中的正则表达式将[cite:lamport94]
替换为\cite{lamport94}
。
String input = "how easy it is to create a well structured document within [cite:lamport94]. You should quickly be able to see."
String output = "how easy it is to create a well structured document within \cite{lamport94}. You should quickly be able to see."
答案 0 :(得分:4)
以下是您可以使用的代码。它将使用“:”分隔符<:p>捕获方括号内的任何字母数字字符串
var input = "how easy it is to create a well structured document within [cite:lamport94]. You should quickly be able to see.";
var rxReg = new Regex(@"\[(\w+):(\w+)]");
var result = rxReg.Replace(input, @"\$1{$2}");
输出:
how easy it is to create a well structured document within \cite{lamport94}. You should quickly be able to see.
顺便说一句,如果括号内只有[a-zA-Z0-9_]
个字符,则可以将\w
扩展为[\w.:-]
(我更喜欢匹配mm.xxx
的模式,或{ {1}}或xx-yy
字符串。如果需要,请添加更多字符串(请注意连字符必须保留在字符类的末尾以保留字面连字符。)
要仅限于xx:yyyy
,请使用它而不是第一个cite
:
\w
答案 1 :(得分:1)
您可以使用以下内容进行匹配:
\[(cite):(.*?)\] //assuming you always have cite as common
并替换为
\$1{$2}