我需要替换一个在其他实例中有实例的字符串,但如果它在花括号内,则忽略替换任何字符串。
我尝试了以下内容:
public Validation()
{
_Validations = new List<Action<object>>
{
ValidateNull,
ValidateDecimal,
ValidateIsNumber,
ValidateRange,
};
}
public bool Validate(Control control, object value)
{
try
{
_Validations.ForEach(c => c(value));
return true;
}
catch (Exception e)
{
ErrorText = e.Message;
return false;
}
}
private void ValidateNull(object value)
{
if (value == null && !_IsAllowNull)
throw new Exception("Please provided valid number without a decimal point.");
}
private void ValidateRange(object value)
{
if (value.ToInt() < _minValue || value.ToInt() > _maxValue)
throw new Exception("Value should not be greater than " + _maxValue + " or less than " + _minValue);
}
private static void ValidateIsNumber(object value)
{
if (!value.IsNumber())
throw new Exception("Please provided valid number without a decimal point.");
}
private static void ValidateDecimal(object value)
{
if (value.ToString().Contains("."))
throw new Exception("Decimal value is not allowed");
}
但我需要将替换看起来像这样:str = "replace {replace} test replacesreplace"
str.replace(/{[^}]*}|(replace(s)?)/g, "%")
// % % test %%
str = "replace {replace} test replacesreplace"
str.replace(/{[^}]*}|(replace(s)?)/g, "$1"+"%")
// replace% % test replaces%replace%
有人可以建议如何在Javascript中执行此操作吗?
答案 0 :(得分:3)
您可以使用String.replace()
的功能。如果找到了捕获,则返回支撑的东西,否则返回%
。
var str = "replace {replace} test replacesreplace";
str = str.replace(/({[^}]*})|replaces?/g, function($0, $1) {
return typeof $1 != 'undefined' ? $1 : "%";
});
document.write(str);
&#13;
答案 1 :(得分:1)
使用否定前瞻
(?!\{)replace(?!\})
(?!\{)
:否定前瞻 - 断言无法匹配{
字面replace
:匹配replace
字符串(?!\})
:否定前瞻 - 断言无法匹配}
字面Javascript演示
var str = "replace {replace} test replacesreplace";
var replacedStr = str.replace(/(?!\{)replace(?!\})/g, "%");
document.write(replacedStr);
&#13;