Javascript Regex - 替换所有匹配字符串的出现,除了括号之间的任何字符串

时间:2015-11-06 04:06:20

标签: javascript regex string replace

我需要替换一个在其他实例中有实例的字符串,但如果它在花括号内,则忽略替换任何字符串。

我尝试了以下内容:

    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中执行此操作吗?

2 个答案:

答案 0 :(得分:3)

您可以使用String.replace()的功能。如果找到了捕获,则返回支撑的东西,否则返回%

&#13;
&#13;
var str = "replace {replace} test replacesreplace";

str = str.replace(/({[^}]*})|replaces?/g, function($0, $1) {
 return typeof $1 != 'undefined' ? $1 : "%";
});

document.write(str);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用否定前瞻

Regex Demo

(?!\{)replace(?!\})
  1. (?!\{):否定前瞻 - 断言无法匹配{字面
  2. replace:匹配replace字符串
  3. (?!\}):否定前瞻 - 断言无法匹配}字面
  4. Javascript演示

    &#13;
    &#13;
    var str = "replace {replace} test replacesreplace";
    var replacedStr = str.replace(/(?!\{)replace(?!\})/g, "%");
    
    document.write(replacedStr);
    &#13;
    &#13;
    &#13;

相关问题