正则表达式中的空白问题

问题描述 投票:0回答:3

我正在使用一个简单的 Perl 脚本来解析 XML 并将其转换为可用的 SQL。我当前的 SQL 行是这样的:

INSERT INTO table VALUES ('data1', 'data2', 'data3', ); 

显然我需要删除末尾的逗号。听起来很简单,但我就是无法让正则表达式找到它。我尝试过

s/,\s+\)/\)/
但当我运行它时并没有改变任何东西。奇怪的是,
s/,\s+/WTF/
也没有修改任何内容,而它应该替换所有逗号及其旁边的空格。但是当我运行
s/\s+\)/something/
时,它正确地找到并替换了行末尾的右括号。所以显然逗号后面的空白字符是一些奇怪的幽灵字符,我无论如何也找不到。即使使用
.
表情也不行。

真正奇怪的是,当我在 Notepad++ 中使用正则表达式选项在文档上查找时,当我输入

,\s+\)
时,它会完美地找到所有这些内容,但 Perl 正则表达式中完全相同的序列却找不到它们。

我怀疑它与

\r
有关(我使用的是Windows),因为我之前删除了
\n
字符,但在整个sql文件中找不到
\r

提前感谢您的帮助,这让我很困惑。

regex perl whitespace
3个回答
8
投票

首先,

$ perl -E 'my $foo = "bar, baz"; $foo =~ s/,\s+/WTF/; say $foo'
barWTFbaz

它确实有效。 (对于 perl 5.8 及之前版本,将其更改为 -e 和

print "$foo\n"

第二,你做错了。而不是做类似的事情:

$values = "'$values[0]', ";
$values .= "'$values[1]', ";
⋮

你应该做:

$values = join(q{,}, map("'$_'", @values)); # map adds 'quotes'; join adds commas

第三,你甚至不应该这样做,你应该使用占位符:

# note specifying the column names, its a good idea! Schema change.
my $query = "INSERT INTO table (col1, col2, col3) VALUES (?,?,?)";
my $sth = $dbh->prepare($query);
$sth->execute(@values);

2
投票

这个表达怎么样:

s/,\W+)/)

0
投票

第一个正则表达式似乎对我有用。 我想说也许字符串中的某些内容没有正确转义,或者某个地方存在另一个小错误。 我打算建议将正则表达式锚定到字符串的末尾。 通常,如果您可以将正则表达式锚定到行的开头或结尾,则它会工作得更好一些。 这是包含您的工作正则表达式的代码,下面是我的建议。

#!/usr/bin/perl -w

my $s = qq(INSERT INTO table VALUES ('data1', 'data2', 'data3', ););
my $fixedString;

print "$s\n";
$fixedString = $s =~ s/,\s+\)/\)/r; #r modifier means dont change original string, so I can use it again later
print "$fixedString\n";
print "this approach is working for me\n";
print "------------\n\n";

#working for me.  Maybe something is not escaped properly.  This was my planned suggestion, anchor the regex to the end of the line
print "different approach\n$s\n";
$fixedString = "";
$fixedString = $s =~ s/, +\)\;$/\)\;/r; #anchored at the end of the line after the semicolon, regex's often work better when you can anchor them
print  "$fixedString\n";
print "also working\n";
print "------------\n";

输出看起来像这样

$ perl fixSqlStatement.pl
INSERT INTO table VALUES ('data1', 'data2', 'data3', );
INSERT INTO table VALUES ('data1', 'data2', 'data3');
this approach is working for me
------------

different approach
INSERT INTO table VALUES ('data1', 'data2', 'data3', );
INSERT INTO table VALUES ('data1', 'data2', 'data3');
also working
------------
© www.soinside.com 2019 - 2024. All rights reserved.