晚上好,
我正在尝试查找所有出现的以“{”开头并以“}”结尾的字符串,然后用不同的字符串替换它们。为了帮助说明,以下是一个简短的例子。
string exampleString = "My name is {Name}. I was born as {Race}. I am {Height} tall. My hair is {HairLength}.";
在上面的字符串中,我想删除{Name},{Race},{Height}和{HairLength},并将其替换为其他内容。我觉得我现在遇到子串很麻烦,因为我似乎无法将字符串拆分到正确的位置,只是为了删除括号中的单词。
我觉得我有点用这个烧了自己,并且犯了一些愚蠢的错误,但我现在看不到它们。我用来分割字符串的(杂乱)代码如下。
public static string ForPlayer ( string originalString )
{
string richText = originalString;
PropertyInfo propertyInfo;
int openingInstance = 0;
int closingInstance = 0;
int length = 0;
foreach ( char c in originalString.ToCharArray ())
{
if ( c == '{' )
{
openingInstance = length;
}
if ( c == '}' && openingInstance > closingInstance )
{
int lastBrace = closingInstance;
closingInstance = length;
int lengthToNextBrace = originalString.IndexOf ( "{", closingInstance ) - closingInstance - 1;
string richInstance = originalString.Substring ( openingInstance + 1, closingInstance - openingInstance - 1 );
propertyInfo = Player.player.GetType ().GetProperty ( richInstance );
if ( propertyInfo != null )
{
string beginning;
string end;
if ( lastBrace == 0 )
{
beginning = originalString.Substring ( 0, openingInstance );
} else
{
beginning = originalString.Substring ( closingInstance + 1, openingInstance - lastBrace );
}
if ( lengthToNextBrace > -1 )
{
end = originalString.Substring ( closingInstance + 1, lengthToNextBrace );
} else
{
end = originalString.Substring ( closingInstance + 1, originalString.Length - closingInstance - 1 );
}
richText = beginning + propertyInfo.GetValue ( Player.player, null ) + end;
UnityEngine.Debug.Log ( beginning + propertyInfo.GetValue ( Player.player, null ) + end );
}
}
length += 1;
}
return richText;
}
我得到了:
DEBUG: "My name is default. I was born as "
DEBUG: ". I am {Height} tdefault. I am "
DEBUG: " tall. Mdefault tall. My hair is "
ERROR: "ArgumentOutOfRangeException: startIndex + length > this.length"
我想:
My name is defaultName. I was born as
defaultRace. I am
defaultHeight tall. My hair is
defaultHairLength.
===编辑===
谢谢大家的答案!不幸的是,我不知道我要替换的字符串是什么,并且有很多可能性,如果可能的话,我宁愿使用我当前通过反射找到它的方法。
答案 0 :(得分:2)
试试这个:
public static string ForPlayer(string originalString)
{
return
Regex
.Matches(originalString, "{(.*?)}")
.Cast<Match>()
.Select(x => x.Groups[1].Value)
.Select(x => new
{
From = x,
To = Player.player
.GetType()
.GetProperty(x)
.GetValue(Player.player)
.ToString()
})
.Aggregate(originalString, (a, x) => a.Replace("{" + x.From + "}", x.To));
}
我使用以下测试类对您的示例输入"My name is {Name}. I was born as {Race}. I am {Height} tall. My hair is {HairLength}."
进行了测试:
public class Player
{
public string Name {get; set; }
public string Race {get; set; }
public string Height {get; set; }
public int HairLength {get; set; }
}
var player = new Player()
{
Name = "Fred", Race = "English", Height = "Tall", HairLength = 33
};
得到了这个结果:
"My name is Fred. I was born as English. I am Tall tall. My hair is 33."
这更好:
public static string ForPlayer(string originalString)
{
return
Regex
.Replace(originalString, "{(.*?)}", m =>
Player.player
.GetType()
.GetProperty(m.Groups[1].Value)
.GetValue(Player.player)
.ToString());
}
答案 1 :(得分:1)
如果占位符实际上是对象的属性名称,那么您可以使用FormatWith
来完成这项工作。
string exampleString = "My name is {Name}. I was born as {Race}. I am {Height} tall. My hair is {HairLength}.";
string replacedString = exampleString.FormatWith(Player.player);
答案 2 :(得分:1)
这是一个干净,简单的版本。它使用IndexOf
方法查找大括号而不是迭代字符。它还使用StringBuilder
来避免在可能的情况下复制字符串。
public static string ForPlayer(string originalString, object player)
{
var type = player.GetType();
var sb = new StringBuilder(originalString.Length);
var lastEnd = 0; // after the last close brace
var start = originalString.IndexOf('{'); // start brace
while (start != -1) // go until we run out of open braces
{
var end = originalString.IndexOf('}', start + 1); // end brace
if (end == -1) // if there's a start brace but no end, just quit
break;
// copy from the end of the last string to the start of the new one
sb.Append(originalString, lastEnd, start - lastEnd);
// get the name of the property to look up
var propName = originalString.Substring(start + 1, end - start - 1);
// add in the property value
sb.Append(type.GetProperty(propName).GetValue(player, null));
lastEnd = end + 1; // move the pointer to the end of the last string
start = originalString.IndexOf('{', lastEnd); // find the next start
}
// copy the end of the string
sb.Append(originalString, lastEnd, originalString.Length - lastEnd);
return sb.ToString();
}
答案 3 :(得分:-1)
var replacement=new Dictionary<string,string>{
{"Name","defaultName"},
{"Race","defaultRace"},
{"Height","defaultHeight"},
{"HairLength","defaultHairLength"}
};
string exampleString="My name is {Name}. I was born as {Race}. I am {Height} tall. My hair is {HairLength}.";
foreach(var kv in replacement)
{
exampleString = exampleString.Replace("{" + kv.Key + "}", kv.Value);
}
从PetSerAl窃取第一部分
答案 4 :(得分:-1)
这是我使用正则表达式的方法。
using System.Text.RegularExpressions;
...
class Program
{
static int occurence = 0;
static string[] defValues = new string[] { "DefName", "DefRace", "DefHeight", "DefHair" };
static string ReplaceWithDefault(Match m)
{
if (occurence < defValues.Length)
return defValues[occurence++];
else
return "NO_DEFAULT_VALUE_FOUND";
}
static void Main(string[] args)
{
string exampleString = "My name is {Name}. I was born as {Race}. I am {Height} tall. My hair is {HairLength}.";
string replaced = Regex.Replace(exampleString, "\\{[^\\}]+\\}", new MatchEvaluator(ReplaceWithDefault));
occurence = 0;
Console.WriteLine(exampleString);
Console.WriteLine(replaced);
}
}