查找并替换,介于2个字符之间

时间:2019-08-27 07:33:55

标签: regex csv replace find

所以我有一个CSV文件,例如

 SELECT Item1,
case when Item2 like '%.0' then 
substring(Item2 , 1 , PATINDEX('%[^0-9]%', Item2) - 1) else Item2  end as Item2,
Item3    --- cast over here
 FROM OPENJSON( @DataTable  )
 WITH (Item1 NVARCHAR(100) '$.Item1'
        , Item2 NVARCHAR(100) '$.Item2'
        , Item3 NVARCHAR(100) '$.Item3'    
        );


For example---

Declare @query varchar(max) 

set @query = '7512345671195.00'

select substring(@query, 1 , PATINDEX('%[^0-9]%', @query)-1)


Result
-------
7512345671195

我要在这些字符||之间替换, ||。 所以我期待

2019-07-25 00:00:00,1014488,2019-07-25 12:24:12,112629,Amy,Flutmus,84004,GM,0001,2.99,312,FFO & CS PLATE        ||22,10999,90027,90062||Sand w/ Options,1,0,0.2,18.85,0,1

1 个答案:

答案 0 :(得分:0)

您可以使用re.sub捕获||之间的所有字符串,然后将,替换为* s:

import re

value = "2019-07-25 00:00:00,1014488,2019-07-25 12:24:12,112629,Amy,Flutmus,84004,GM,0001,2.99,312,FFO & CS PLATE        ||22,10999,90027,90062||Sand w/ Options,1,0,0.2,18.85,0,1"

pattern = re.compile(r'\|\|(.+)\|\|')

cleaned_value = pattern.sub(lambda match: match.group().replace(",", "*"), value)

print(cleaned_value.replace(r'||', ','))