简体   繁体   English

在单引号之间替换文本

[英]Replacing text between single quotes

I'm trying to replace some text in an Excel formula using FlexCel, C# and Regex, but single quotes appear to be tricky from the googling I've done. 我正在尝试使用FlexCel,C#和Regex替换Excel公式中的一些文本,但是从我执行的谷歌搜索看来,单引号似乎很棘手。
The string is like this; 字符串是这样的;
"=RIGHT(CELL(\\"filename\\",'C.Whittaker'!$A$1),LEN(CELL(\\"filename\\",'C.Whittaker'!$A$1))-FIND(\\"]\\",CELL(\\"filename\\",'C.Whittaker'!$A$1)))"

I want to replace C.Whittaker with another name. 我想用另一个名字代替C.Whittaker It's always going to be First Initial . 它始终是First Initial。 Last Name and it's always going to be inside single quotes. 姓氏,它总是用单引号引起来。

I've got this regex matching; 我有这个正则表达式匹配; (?:')[^\\"]+(?:')
I thought the (?:') means that regex matches it, but then ignores it for a replace, yet this doesn't seem to be the case. 我以为(?:')表示正则表达式与之匹配,但随后将其忽略以进行替换,但事实并非如此。 Suspect the issue is to do with how strings are handled, but it's a bit beyond me. 怀疑问题在于如何处理字符串,但这超出了我的范围。

(?:...) is a non-capturing group; (?:...)是一个非捕获组; it doesn't capture what it matches (that is, it doesn't make that part of the string available later by means of a backreference), but it does consume it. 它不会捕获它匹配的内容(也就是说,它不会在以后通过反向引用使字符串的那部分可用),但是它确实消耗了它。 What you're thinking of is lookarounds, which don't consume what they match. 您正在考虑的是环顾四周,它不会消耗它们匹配的内容。

(?<=')[^']+(?=')

But do you really need them? 但是您真的需要它们吗? You might find it simpler to consume the quotes and then add them to the replacement string. 您可能会发现使用引号然后将其添加到替换字符串中会更简单。 In other words, replace '[^']+' with 'X.Newname' . 换句话说,用'X.Newname'替换'[^']+' 'X.Newname'

I believe you need to escape your character you want Regex to take it literally... 我相信您需要逃脱自己的角色,希望Regex从字面上理解它...

ie: (?:') becomes (?:\\') 即:( (?:')变为(?:\\')

Do you really need to use regex? 您真的需要使用正则表达式吗? Regex is good for complex cases where speed is important, but it leads to difficult to maintain code. 正则表达式适用于速度很重要的复杂情况,但它导致难以维护代码。

Try this instead: 尝试以下方法:

var formula2 =
    String.Join("'", formula
        .Split(new [] { '\'' })
        .Select((x, n) => n % 2 == 1 ? "new name here" : x));

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

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