2

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!

0

3 Answers 3

5

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;
Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.