简体   繁体   English

从 C# 中的字符串中提取特定文本

[英]Extracting specific text from a string in C#

This is the string: "WATERMARK('Hello!')"这是字符串: "WATERMARK('Hello!')"

What I want to extract is "Hello!"我要提取的是"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) ,不包括"WATERMARK"和括号( 'Hello!' ,可以是任何东西,所以我需要从这里提取文本,最后我需要将WATERMARK('')替换为原始字符串中的任何内容)

How can I do this?我怎样才能做到这一点?

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

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.你可以只做一个while true循环来迭代字符串然后做一个if语句,这样当你到达第一个时(你可以开始将字符存储在一个新字符串中。然后继续检查while true循环)然后用 if 语句中断 while 循环。 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!然后通过使用 for(size--) 循环来反转字符串的顺序,并将字符放入一个新字符串中,然后在新的字符串中你的答案就是你提取的文本!

Here's one approach that doesn't require RegEx.这是一种不需要 RegEx 的方法。

Assuming you've provided all the details, the result will always be WATERMARK('') no matter what the original string contained.假设您提供了所有详细信息,无论原始字符串包含什么,结果都将始终为WATERMARK('')

This method includes some basic error checking, and returns false if the values could not be extracted.此方法包括一些基本的错误检查,如果无法提取值,则返回 false。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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