1

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.
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. It's always going to be 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.

4

3 回答 3

1

(?:...)是非捕获组;它不会捕获它匹配的内容(也就是说,它不会在以后通过反向引用使字符串的那部分可用),但它确实会消耗它。您正在考虑的是环顾四周,它不会消耗它们匹配的内容。

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

但是你真的需要它们吗?您可能会发现使用引号然后将它们添加到替换字符串更简单。换句话说,替换'[^']+''X.Newname'

于 2013-10-30T01:02:52.243 回答
0

你真的需要使用正则表达式吗?正则表达式适用于速度很重要的复杂情况,但会导致代码难以维护。

试试这个:

var formula2 =
    String.Join("'", formula
        .Split(new [] { '\'' })
        .Select((x, n) => n % 2 == 1 ? "new name here" : x));
于 2013-10-30T01:14:42.707 回答
0

我相信你需要逃避你想要正则表达式从字面上理解的角色......

即:(?:') 变成(?:\')

于 2013-10-30T00:12:51.647 回答