gpt4 book ai didi

c# - 替换引号之间的任何字符串

转载 作者:可可西里 更新时间:2023-11-01 08:27:00 26 4
gpt4 key购买 nike

问题:

无法找到一种一致的方法来用我想要的特定字符串替换引号之间的随机字符串。任何帮助将不胜感激。

示例:

String str1 = "test=\"-1\"";

应该变成

String str2 = "test=\"31\"";

还为

工作
String str3 = "test=\"foobar\"";

基本上我想转这个

String str4 = "test=\"antyhingCanGoHere\"";

进入这个

String str4 = "test=\"31\"";

尝试过:

Case insensitive Regex without using RegexOptions enumeration

How do you do case-insensitive string replacement using regular expressions?

Replace any character in between AnyText: and <usernameredacted@example.com> with an empty string using Regex?

Replace string in between occurrences

Replace a String between two Strings

当前代码:

    Regex RemoveName = new Regex("(?VARIABLE=\").*(?=\")", RegexOptions.IgnoreCase);
String convertSeccons = RemoveName.Replace(ruleFixed, "31");

返回错误:

System.ArgumentException was caught
Message=parsing "(?VARIABLE=").*(?=")" - Unrecognized grouping construct.
Source=System
StackTrace:
at System.Text.RegularExpressions.RegexParser.ScanGroupOpen()
at System.Text.RegularExpressions.RegexParser.ScanRegex()
at System.Text.RegularExpressions.RegexParser.Parse(String re, RegexOptions op)
at System.Text.RegularExpressions.Regex..ctor(String pattern, RegexOptions options, Boolean useCache)
at System.Text.RegularExpressions.Regex..ctor(String pattern, RegexOptions options)
at application.application.insertGroupID(String rule) in C:\Users\winserv8\Documents\Visual Studio 2010\Projects\application\application\MainFormLauncher.cs:line 298
at application.application.xmlqueryDB(String xmlSaveLocation, TextWriter tw, String ruleName) in C:\Users\winserv8\Documents\Visual Studio 2010\Projects\application\application\MainFormLauncher.cs:line 250
InnerException:

找到答案

string s = Regex.Replace(ruleFixed, "VARIABLE=\"(.*)\"", "VARIABLE=\"31\"");
ruleFixed = s;

我在 Replace any character in between AnyText: and with an empty string using Regex? 处找到了此代码示例?这是我之前发布的链接之一,只是跳过了这个语法,因为我认为它不能处理我需要的东西。

最佳答案

我不知道我的理解是否正确,但是如果你想替换 string 中的所有字符,为什么不使用简单的正则表达式

String str = "test=\"-\"1\"";

Regex regExpr = new Regex("\".*\"", RegexOptions.IgnoreCase);
String result = regExpr.Replace(str , "\"31\"");

Console.WriteLine(result);

打印:

test="31"

注意:您可以利用普通的旧XAttribute

String ruleFixed = "test=\"-\"1\"";

var splited = ruleFixed.Split('=');
var attribute = new XAttribute(splited[0], splited[1]);

attribute.Value = "31";

Console.WriteLine(attribute);//prints test="31"

关于c# - 替换引号之间的任何字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14224790/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com