Trent
Trent

Reputation: 1593

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.
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.

Upvotes: 1

Views: 349

Answers (3)

Enigmativity
Enigmativity

Reputation: 117175

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));

Upvotes: 0

Alan Moore
Alan Moore

Reputation: 75272

(?:...) 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'.

Upvotes: 1

Kyle C
Kyle C

Reputation: 1637

I believe you need to escape your character you want Regex to take it literally...

ie: (?:') becomes (?:\')

Upvotes: 0

Related Questions