Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to replace begin and end of string

Tags:

c#

.net

regex

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!

like image 210
Gavin Osborn Avatar asked Feb 20 '26 02:02

Gavin Osborn


2 Answers

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;
like image 111
Cameron Avatar answered Feb 22 '26 16:02

Cameron


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.

like image 42
lc. Avatar answered Feb 22 '26 16:02

lc.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!