我有一个字符串,我正在寻找用EUR
替换€
的方法,但仅当EUR
与int
一起编写时。
E.g。
string str = "EUR is einen groß geld 10EUR";
变为
str = "EUR ist einen groß geld 10€"
答案 0 :(得分:1)
你可以这样做,我在这里拍了几张欧元
代码
string str = "EUR is einen groß 90EUR geld 10EUR";
var pattern = @"(\d+)(EUR)";
var replaced = System.Text.RegularExpressions.Regex.Replace(str, pattern, "$1€");
这是结果
replaced = "EUR is einen groß 90€ geld 10€"
答案 1 :(得分:1)
尽管 Regex 可能是走到这里的方式,但在处理这类情况时,依赖它可能会使你的技能变得迟钝。
总是很有趣(如果你有时间)尝试用旧的字符串迭代来解决问题:)。下面的代码应该完成这项工作(还没有对它进行过广泛的测试),它可能比使用你可能不理解的正则表达式模式字符串更有启发性(你不会&#39)如果你这样做,可以问这个问题。)
static class Extensions
{
public static string SubstituteCurrencyString(this string input, string currencyString, string currencySymbol, bool onlyWhenPrecededByDigits = true)
{
if (input == null)
throw new ArgumentNullException("input");
if (currencyString == null)
throw new ArgumentNullException("currencyString");
if (currencySymbol == null)
throw new ArgumentNullException("currencySymbol");
if (string.IsNullOrWhiteSpace(input))
return input;
if (!onlyWhenPrecededByDigits)
return input.Replace(currencyString, currencySymbol);
bool parsingNumber = false;
StringBuilder b = new StringBuilder(input.Length);
using (var stringEnumerator = input.GetEnumerator())
{
int index = -1;
while (stringEnumerator.MoveNext())
{
++index;
if (char.IsDigit(stringEnumerator.Current))
{
parsingNumber = true;
}
else if (stringEnumerator.Current == CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator[0])
{
//Do nothing. If we are "parsing" a number, we keep on "parsing" a number. If were not, we are not.
}
else if (stringEnumerator.Current == CultureInfo.CurrentCulture.NumberFormat.CurrencyGroupSeparator[0])
{
//Do nothing. If we are "parsing" a number, we keep on "parsing" a number. If were not, we are not.
}
else
{
if (parsingNumber && checkCurrencyString(input, currencyString, index))
{
b.Append(currencySymbol);
for (int i = 0; i < currencyString.Length; ++i)
{
stringEnumerator.MoveNext();
++index;
}
}
parsingNumber = false;
}
if (index < input.Length)
{
b.Append(stringEnumerator.Current);
}
}
}
return b.ToString();
}
private static bool checkCurrencyString(string input, string currencyString, int index)
{
Debug.Assert(input != null);
Debug.Assert(currencyString != null);
Debug.Assert(0 < index && index < input.Length);
if (input.Length - index < currencyString.Length)
return false;
var potentialCurrenyString = input.Substring(index, currencyString.Length);
return string.Compare(potentialCurrenyString, currencyString, false) == 0;
}
}
答案 2 :(得分:0)
Regex r = new Regex(@"\d+(?<toreplace>EUR)");
此正则表达式将与您描述的方案相匹配。我会把更换作为练习留给你。
答案 3 :(得分:0)
尝试更通用。有一个字典,货币作为键,符号作为值。 并且使用RegEx确实用字典中的值替换货币后跟数字