Home > Blockchain >  Extracting specific text from a string in C#
Extracting specific text from a string in C#

Time:09-23

This is the string: "WATERMARK('Hello!')"

What I want to extract is "Hello!", excluding the "WATERMARK" and the brackets ('Hello!', can be anything so I need to extract the text from here, and for the last I need to replace WATERMARK('') with nothing in the original string)

How can I do this?

CodePudding user response:

You can use regex to capture the string inside.
Also is the regex value gonna capture strings inside

WATERMARK("")

Here's an example of the regex value (I do not know if it works.)

/(?<=WATERMARK(')[\S\s]*(?='))/i

CodePudding user response:

u can just make a while true loop to iterate over the string then make a if statement so when you get to the 1st ( u can start storing the charachters in a new string. then keep checking in the while true loop for the ) and then break the while loop witha if statement. then reverse the order of the string by usin a for(size--) loop and putting the charachters into a new string and bam thnats ur answer right in the new strinfg is ur extracted text!

CodePudding user response:

Here's one approach that doesn't require RegEx.

Assuming you've provided all the details, the result will always be WATERMARK('') no matter what the original string contained.

This method includes some basic error checking, and returns false if the values could not be extracted.

private const string Prefix = "WATERMARK('";
private const string Suffix = "')";

bool RemoveWatermark(string s, out string value, out string result)
{
    int length = s.Length - Prefix.Length - Suffix.Length;
    if (length > 0)
    {
        value = s[Prefix.Length..(Prefix.Length   length)];
        result = string.Concat(Prefix, Suffix);
        return true;
    }

    value = string.Empty;
    result = string.Empty;
    return false;
}
  •  Tags:  
  • c#
  • Related