RegEx匹配分隔符之间或开头或结尾的字符串

Kev*_*ynn 1 regex language-agnostic

我正在处理CSV文件,并希望搜索和替换字符串,只要它与列中的完全匹配即可.例如:

xxx,Apple,Green Apple,xxx,xxx
Apple,xxx,xxx,Apple,xxx
xxx,xxx,Fruit/Apple,xxx,Apple
Run Code Online (Sandbox Code Playgroud)

我想替换'Apple',如果它是列中的EXACT值(如果它包含在另一列中的文本中,我不想替换).我看不出如何使用单个表达式(可能不可能?).

所需的输出是:

xxx,GRAPE,Green Apple,xxx,xxx
GRAPE,xxx,xxx,GRAPE,xxx
xxx,xxx,Fruit/Apple,xxx,GRAPE
Run Code Online (Sandbox Code Playgroud)

所以我想要的表达式是:匹配输入的开头或逗号,后跟所需的字符串,后跟逗号或输入的结尾.

你不能把^或$放在字符类中,所以我尝试了\ A和\ Z但是没有用.

([\A,])Apple([\Z,])
Run Code Online (Sandbox Code Playgroud)

遗憾的是,这不起作用.我可以用一个正则表达式做到这一点吗?这似乎是一个常见的问题.

Jer*_*rry 5

它取决于您的语言,但如果您使用的语言支持外观,那么您将使用以下内容:

(?<=,|^)Apple(?=,|$)
Run Code Online (Sandbox Code Playgroud)

替换为GRAPE.

否则,你将不得不放回逗号:

(^|,)Apple(,|$)
Run Code Online (Sandbox Code Playgroud)

要么

(\A|,)Apple(,|\Z)
Run Code Online (Sandbox Code Playgroud)

并替换为:

\1GRAPE\2
Run Code Online (Sandbox Code Playgroud)

要么

$1GRAPE$2
Run Code Online (Sandbox Code Playgroud)

取决于支持的内容.

以上是原始正则表达式(和替换)字符串.必要时逃脱.

注意:后一种解决方案的缺点是它不能用于以下字符串:

xxx,Apple,Apple,xxx,xxx
Run Code Online (Sandbox Code Playgroud)

自从第一次Apple消耗之后的逗号.如果你有这种情况,你必须最多两次调用正则表达式替换.


哦,我忘了提,你可以有一些'混合',因为某些语言对于lookbehinds有不同程度的支持(在所有下面^\A,$并且\Z,\1并且$1可以互换,所以我不会比它已经更长是):

(?:(?<=,)|(?<=^))Apple(?=,|$)
Run Code Online (Sandbox Code Playgroud)

对于那些外观不能宽度可变的人来说,替换为GRAPE.

(^|,)Apple(?=,|$)
Run Code Online (Sandbox Code Playgroud)

以上是支持前瞻但不支持外观的方法.替换为\1Apple.