如果存在多个,则留下一个REGEX

时间:2016-06-29 19:40:47

标签: regex python-2.7

我必须过滤它们看起来像的路径:

  • some_path//rest
  • some_path/rest
  • some_path\\\\rest
  • some_path\rest

我需要用FILTER

替换some_path // rest
  • some_path/rest//我想要FILTER/
  • some_path/rest\\我想要FILTER\
  • some_path/rest我想要FILTER
  • some_path/rest/我想要FILTER/
  • some_path/rest\我想要FILTER\

我正在使用some_path[\\\\\\\/]+rest来匹配中间,如果我在最后使用它会消耗所有路径分隔符。

我事先并不知道分隔符是/还是\\它是否可以在单个路径中混合。 some_path/rest\some_more//and/more\\\\more

2 个答案:

答案 0 :(得分:1)

考虑使用反向引用。请记住,使用Python,您会看到\在输出中使用第二个\进行转义。这个例子似乎可以满足您的需求:

>>> for test in ('some_path/rest//','some_path/rest\\','some_path/rest','some_path/rest/','some_path/rest\\'):
...     re.sub(r"some_path[\/]+rest([\/]?)\1*", r"FILTER\1", test)
... 
'FILTER/'
'FILTER\\'
'FILTER'
'FILTER/'
'FILTER\\'
>>> 

\1是对前一个()群组的反向引用。在搜索中,它正在搜索该项目的任意数量的匹配项。在替换中,它只是添加一个项目。

答案 1 :(得分:0)

你可以通过使用简单的(没有后退参考)来替换术语。

使用此正则表达式搜索:

    private Connection con ;

    private Statement stmt;


    public void connect ( String path ){

        try {
            Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");

            this.con = DriverManager.getConnection(path, "", "");

            this.stmt = con.createStatement();

        } catch (SQLException ex) {
            System.err.println("SQLException: " + ex.getMessage());
        } 
        catch (ClassNotFoundException e) {

            System.err.println("classnotfoundException: " + e.getMessage());


        }
    }

并将该匹配替换为some_path[\\\\/]+rest(?:([\\\\/])(?=\1))?

'FILTER'

加倍时,通过匹配(即消费)尾部斜杠 来工作。

为了允许在没有尾部斜杠的情况下,通过包裹re.sub(r"some_path[\\\\/]+rest(?:([\\\\/])(?=\1))?", 'FILTER', path) (非捕获,因此后引用为(?:...)?而不是{{1},可以使尾随斜杠的匹配成为可选哪个更难阅读。

请注意,正则表达式中不需要那么多反斜杠。

这是一些测试代码:

\1

输出:

\2
相关问题