我在使用正则表达式时遇到问题我需要在Notepad ++中执行此查找/替换。我需要进行几次单独的搜索才能完成整个过程。
基本上我需要在CSV的每一行的开头和结尾添加|
,并将所有,
替换为|
。然后,在任何只有1个字符的值上,我需要在每一个字符周围放置两个空格(" A"变为" A")
来源:
col1,col2,col3,col4,col5,col6
name,desc,something,else,here,too
another,,three,,,
single,characters,here,a,b,c
last,line,here,,almost,
结果:
|col1|col2|col3|col4|col5|col6|
|name|desc|something|else|here|too|
|another||three||||
|single|characters|here| a | b | c |
|last|line|here||almost||
将|
添加到行的开头和结尾非常简单,将,
替换为|
显然很简单。但我无法提出正则表达式来查找|x|
x
仅限于一个字符。我确信它很简单,但我是regex的新手。
答案 0 :(得分:4)
正则表达式:
(?:(^)|(?!^)\G)(?:([^\r\n,]{2,})|([^\r\n,]))?(?:(,$)|(,)|($))
替换字符串:
(?{1}|)(?{2}\2)(?{3} \3 )(?{4}||)(?{5}|)(?{6}|)
丑陋,肮脏而长久却有效。
正则表达式解释:
(?: # Start of non-capturing group (a)
(^) # Assert beginning of line (CP #1)
| # Or
(?!^) # //
\G # Match at previous matched position
) # End of non-capturing group (a)
(?: # Start of non-capturing group (b)
([^\r\n,]{2,}) # Match characters with more than 2-char length (any except \r, \n or `,`) (CP #2)
| # Or
([^\r\n,]) # Match one-char string (CP #3)
)? # Optional - End of non-capturing group (b)
(?: # Start of non-capturing group (c)
(,$) # Match `,$` (CP #4)
| # Or
(,) # Match single comma (CP #5)
| # Or
($) # Assert end of line (CP #6)
) # End of non-capturing group (c)
答案 1 :(得分:1)
第一个替换添加|在开头和结尾,并替换逗号:
Search: ^|$|,
Replace: |
第二次替换会增加单个字符匹配的空间:
Search: (?<=[|])([^|])(?=[|])
Replace: $1
在$ 1的左侧和右侧添加空格。
答案 2 :(得分:1)
三步解决方案:
^.+$
替换:|$0|
,
替换:|
(?<=\|)([^|\r\n])(?=\|)
替换: $0