python搜索" \ |"并用"替换"

时间:2018-02-21 20:16:33

标签: python regex escaping

我使用字段分隔符" |"

获取数据
field 1 | field 2 | field 3 

是我得到的常规线。

例外似乎是

field 1 | 2\|2\|2 | field 3

我的python程序应该返回

field 1 | 2 2 2 | field 3

我正在寻找python 2.6正则表达式,用空格\|替换。 我做了很多尝试但主要取代了常规字段分隔符。 最新的尝试是

line = re.sub("\\\\\|", " ", line)

1 个答案:

答案 0 :(得分:0)

<script>
            try {

                var util = {
                    startWith: function (source, search, ignoreCase) {
                        search = this.regExpEscapeSpecialCharacters(search);
                        var ignore = (ignoreCase) ? "gi" : "g";
                        var reg = new RegExp("^" + search + "", ignore);
                        return reg.test(source);
                    },
                    endWith: function (source, search, ignoreCase) {
                        search = this.regExpEscapeSpecialCharacters(search);
                        var ignore = (ignoreCase) ? "gi" : "g";
                        var reg = new RegExp(search + "$", ignore);
                        return reg.test(source);
                    },
                    contain: function (source, search, ignoreCase) {
                        search = this.regExpEscapeSpecialCharacters(search);
                        var ignore = (ignoreCase) ? "gi" : "g";
                        var reg = new RegExp(search, ignore);
                        return reg.test(source);
                    },
                    regExpEscapeSpecialCharacters: function (a) {
                        return  a.toString().replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
                    },
                };

                //EXAMPLES:
                var text = "hello world";
                var search1 = "he";
                var search2 = "ld";

                if (util.startWith(text, search1, true) && util.endWith(text, search2, true)) {
                    alert("match");
                }


            } catch (e) {
                alert(e);

            }

        </script>

字符串方法替换将在此处运行。如果你可以避免使用正则表达式,你会省去头痛。有关详细信息,请参阅the documentation