使用Regex替换字符串

时间:2015-03-13 08:01:47

标签: java regex sed

我正在尝试替换convert(string1,string2) to CAST(<String2> AS <String1>)的所有行为。

INPUT STRING如下:

Insert Into `Collaboration`.`SR_SearchResult`(SearchLinkID,PWUserID,SearchRank) 
        Select distinct lnk.SearchLinkID, Convert(varchar(10),@PWUserID) ,Convert(varchar(10),@rank) from `Collaboration`.`SR_SearchLink` lnk (nolock)
        inner join `Collaboration`.`SR_SearchTag` tg (nolock) on lnk.SearchLinkID = tg.SearchLinkID         
        WHERE @strSearch

期望的输出字符串:

Insert Into `Collaboration`.`SR_SearchResult`(SearchLinkID,PWUserID,SearchRank) 
        Select distinct lnk.SearchLinkID, CAST(@PWUserID AS varchar(10)) ,CAST(@rank AS varchar(10)) from `Collaboration`.`SR_SearchLink` lnk (nolock)
        inner join `Collaboration`.`SR_SearchTag` tg (nolock) on lnk.SearchLinkID = tg.SearchLinkID         
        WHERE @strSearch

我从我身边尝试了很多但却无法做到这一点。请帮帮我。

3 个答案:

答案 0 :(得分:1)

假设您使用的是Java,您可以使用以下正则表达式:convert\((.+?),(.+?)\)并像这样使用它(示例示例here):

String str = "Insert Into Collaboration.SR_SearchResult(SearchLinkID,PWUserID,SearchRank) Select distinct lnk.SearchLinkID, Convert(varchar(10),@PWUserID) ,Convert(varchar(10),@rank) from Collaboration.SR_SearchLink lnk (nolock) inner join Collaboration.SR_SearchTag tg (nolock) on lnk.SearchLinkID = tg.SearchLinkID\n" +
"WHERE @strSearch";
        System.out.println(str.replaceAll("Convert\\((.+?),(.+?)\\)", "CAST($2 AS $1)"));

收率:

Insert Into Collaboration.SR_SearchResult(SearchLinkID,PWUserID,SearchRank) Select distinct lnk.SearchLinkID, CAST(@PWUserID AS varchar(10)) ,CAST(@rank AS varchar(10)) from Collaboration.SR_SearchLink lnk (nolock) inner join Collaboration.SR_SearchTag tg (nolock) on lnk.SearchLinkID = tg.SearchLinkID
WHERE @strSearch

答案 1 :(得分:1)

通过sed。

$ sed 's/\bConvert(\([^,]*\),\([^)]*\))/CAST(\2 AS \1)/gi' file
Insert Into Collaboration.SR_SearchResult(SearchLinkID,PWUserID,SearchRank) Select distinct lnk.SearchLinkID, CAST(@PWUserID AS varchar(10)) ,CAST(@rank AS varchar(10)) from Collaboration.SR_SearchLink lnk (nolock) inner join Collaboration.SR_SearchTag tg (nolock) on lnk.SearchLinkID = tg.SearchLinkID
WHERE @strSearch

要保存所做的更改,您需要添加-i参数,例如sed -i 's//gi'i修饰符有助于执行不区分大小写的匹配。

答案 2 :(得分:0)

认为你在寻找的是:

sed 's/Convert(\(.*\),\(.*\))/CAST(\2 AS \1)/g'