正则表达很难找到

时间:2017-01-24 15:26:46

标签: regex

我想构建一个将在以下元素上运行的正则表达式:

test.stuff;visibility:=reexport,
test.stuff;bundle-version="0.0.0";visibility:=reexport,
test.stuff;bundle-version="0.0.0"
test.stuff,
test.stuff

我的正则表达式的目的是通过bundle-version =“1.2.3”替换bundle-version =“0.0.0”或 add bundle-version =“1.2 0.3" 即可。

更换后应该产生以下元素:

test.stuff;bundle-version="1.2.3";visibility:=reexport,
test.stuff;bundle-version="1.2.3";visibility:=reexport,
test.stuff;bundle-version="1.2.3"
test.stuff;bundle-version="1.2.3",
test.stuff;bundle-version="1.2.3"

目前我有以下正则表达式:

(test.*?)([;]+bundle.*?)?([;,]+.*)

使用此替换模式:

$1;bundle-version="1.2.3"$3

但它不适用于这两个:

test.stuff;bundle-version="0.0.0"   --> becomes test.stuff;bundle-version="1.2.3";bundle-version="0.0.0"
test.stuff    --> not matched

非常感谢任何帮助,谢谢!

编辑:正则表达式只应匹配以“test.stuff”开头的行

2 个答案:

答案 0 :(得分:1)

这在C#/ LinqPad中对我有用:

string s = @"test.stuff;visibility:=reexport,
test.stuff;bundle-version=""0.0.0"";visibility:=reexport,
test.stuff;bundle-version=""0.0.0""
test.stuff,
test.stuff";

string pat = "(test[^;,\n]*)([;,]+bundle[^;,\n]*)?([;,]*.*)?";
string rep ="$1;bundle-version=\"1.2.3\"$3";

string result = Regex.Replace(s,pat,rep)

编辑:将\ n添加到第一组以避免在最后一次“test.stuff”发生后捕获一行。

答案 1 :(得分:0)

我会两次这样做:
1.替换bundle-version="1.2.3" par stuff(?!;bun)
2.替换stuff;bundle-version="1.2.3" par WITH -- input my_table(country,client,msisdn) AS ( SELECT 'MY','A',111 UNION ALL SELECT 'INDIA','A',112 UNION ALL SELECT 'SG','A',113 UNION ALL SELECT 'SG','A',113 UNION ALL SELECT 'SG','A',113 UNION ALL SELECT 'INDIA','A',126 UNION ALL SELECT 'SG','A',113 UNION ALL SELECT 'INDIA','A',116 UNION ALL SELECT 'INDIA','A',120 UNION ALL SELECT 'CH','D',115 UNION ALL SELECT 'CH','D',115 UNION ALL SELECT 'MY','B',117 UNION ALL SELECT 'INDIA','B',118 UNION ALL SELECT 'SG','C',119 UNION ALL SELECT 'CH','D',199 UNION ALL SELECT 'CH','D',199 ) , -- rows occurring more than once dups AS ( SELECT country , client , msisdn FROM my_table GROUP BY country , client , msisdn HAVING COUNT(*) > 1 ) SELECT m.country , m.client , COUNT(DISTINCT m.msisdn) AS 'Number_of_distinct_MSISDN' , COUNT(*) AS 'Total_number_of_MSISDN' , COUNT(DISTINCT d.msisdn) AS total_distinct_MSISDN FROM my_table m LEFT JOIN dups d USING(country,client,msisdn) -- where CAST(time_updated as DATE) = CURRENT_DATE-1 -- and action_status='COMPLETED' and "ACTION" ='CHARGE' GROUP BY m.country , m.client ORDER BY m.country , m.client ; country|client|Number_of_distinct_MSISDN|Total_number_of_MSISDN|total_distinct_MSN CH |D | 2| 4| 2 INDIA |A | 4| 4| 0 INDIA |B | 1| 1| 0 MY |A | 1| 1| 0 MY |B | 1| 1| 0 SG |A | 1| 4| 1 SG |C | 1| 1| 0