简体   繁体   中英

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!

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.

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM