Gavin Osborn
Gavin Osborn

Reputation: 2603

Regular Expression to replace begin and end of string

Consider the following input: BEGINsomeotherstuffEND

I'm trying to write a regular expression to replace BEGIN and END but only if they both exist.

I got as far as:

(^BEGIN|END$)

Using the following c# code to then perform my string replacement:

private const string Pattern = "(^guid'|'$)";
private static readonly Regex myRegex = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture | RegexOptions.Singleline | RegexOptions.IgnoreCase);
var newValue = myRegex.Replace(input, string.empty);

But unfortunately that matches either of those - not only when they both exist.

I also tried:

^BEGIN.+END$

But that captures the entire string and so the whole string will be replaced.

That's about as far as my Regular Expression knowledge goes.

Help!

Upvotes: 2

Views: 5568

Answers (3)

Cameron
Cameron

Reputation: 98746

How about using this:

^BEGIN(.*)END$

And then replace the entire string with just the part that was in-between:

var match = myRegex.Match(input);
var newValue = match.Success ? match.Groups(1).Value : input;

Upvotes: 5

lc.
lc.

Reputation: 116458

I don't think you really need a regex here. Just try something like:

if (str.StartsWith("BEGIN") && str.EndsWith("END"))
    str = "myreplaceBegin" + str.Substring(5, str.Length - 8) + "myreplaceEnd";

From your code, it looks like you just want to remove the beginning and end parts (not replacing them with anything), so you can just do:

if (str.StartsWith("BEGIN") && str.EndsWith("END"))
    str = str.Substring(5, str.Length - 8);

Of course, be sure to replace the indexes with the actual length of what you are removing.

Upvotes: 5

Justin Pihony
Justin Pihony

Reputation: 67075

You cannot use regular expressions as a parsing engine. However, you could just flip this on its head and say that you want what is between:

begin(.*)end

Then, just grab what is in group 1

Upvotes: 0

Related Questions