使用正则表达式转换逗号分隔的字符串对

时间:2011-01-25 11:48:01

标签: regex

我有一个以逗号分隔的first-lastnames列表,我需要将其转换为SQL (逗号后面有空格):

joe, cool

alice, parker

应该成为:

( firstname ='joe' and lastname = 'cool' ) or

( firstname ='alice' and lastname = 'parker' )

如何使用正则表达式实现此目的?

1 个答案:

答案 0 :(得分:1)

在Perl中你可以这样做:

s/(\S+),\s*(\S+)/( firstname ='\1' and lastname = '\2' )/

从命令行:

> perl -pe "s/(\S+),\s*(\S+)/( firstname ='\1' and lastname = '\2' )/" input.txt

输入:

joe, cool
alice, parker

输出:

( firstname ='joe' and lastname = 'cool' )
( firstname ='alice' and lastname = 'parker' )