gpt4 book ai didi

java正则表达式字符串被 "not\"分割

转载 作者:行者123 更新时间:2023-12-01 19:10:32 26 4
gpt4 key购买 nike

实际上我只需要用JAVA编写一个简单的程序来将MySQL INSERTS行转换为CSV文件(每个mysql表等于一个CSV文件)

在JAVA中使用正则表达式是最好的解决方案吗?

我的主要问题是如何正确匹配这样的值:'this is\'cool\'...'(如何忽略转义的')

示例:

INSERT INTO `table1` VALUES ('this is \'cool\'...' ,'some2');
INSERT INTO `table1` (`field1`,`field2`) VALUES ('this is \'cool\'...' ,'some2');

谢谢

最佳答案

假设您的 SQL 语句在语法上有效,您可以使用

Pattern regex = Pattern.compile("'(?:\\\\.|[^'\\\\])*'");

获取匹配所有单引号字符串的正则表达式,忽略其中的转义字符。

解释没有所有这些额外的反斜杠:

'         # Match '
(?: # Either match...
\\. # an escaped character
| # or
[^'\\] # any character except ' or \
)* # any number of times.
' # Match '

给定字符串

'this', 'is a \' valid', 'string\\', 'even \\\' with', 'escaped quotes.\\\''

这匹配

'this'
'is a \' valid'
'string\\'
'even \\\' with'
'escaped quotes.\\\''

关于java正则表达式字符串被 "not\"分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8560546/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com