在sqlite3中使用正则表达式替换字符串的一部分

18

我使用某种方式安装了正则表达式支持

apt-get install sqlite3 sqlite3-pcre

现在我可以在Bash控制台中使用正则表达式查询,例如

DB="somedb.db"
REGEX_EXTENSION="SELECT load_extension('/usr/lib/sqlite3/pcre.so');"
sqlite3 $DB "$REGEX_EXTENSION select * from sometable where name REGEXP '^[a-z]+$'"

但是我该如何使用正则表达式在sqlite查询中更新字符串?

3个回答

13

SQLite默认不提供regex_replace功能,您需要将其作为扩展加载。以下是我成功加载它的方法。

下载这个扩展的C代码(icu_replace)

使用以下命令进行编译

gcc --shared -fPIC -I sqlite-autoconf-3071100 icu_replace.c -o icu_replace.so

在sqlite3中运行下面提到的命令后,在上述命令已运行并创建了一个名为icu_replace.so的文件

SELECT load_extension(' path to icu_replace.so', 'sqlite3_extension_init') from dual;

在此之后,您将能够使用以下功能:

select regex_replace('\bThe\b',x,'M') from dual;

你能解释一下 regex_replace 命令的参数吗?我在任何地方都找不到相关信息。 - TSG
regex_replace(<正则表达式>, <源字符串>, <替换字符串>). 替换字符串使用 '$' 前缀. - Ravi N.

3
以下是使用动态库支持构建最新的sqlite,并编译 ICU扩展regex_replace扩展。它还假定使用基于Debian的Linux发行版:
sudo apt build-dep sqlite3 # fetches dependencies to compile sqlite3

mkdir sqlite-compilation
cd    sqlite-compilation

wget -O sqlite.tar.gz https://www.sqlite.org/src/tarball/sqlite.tar.gz?r=release

tar xzf sqlite.tar.gz

mkdir build
cd    build
  ../sqlite/configure
  make OPTS='-DSQLITE_ENABLE_LOAD_EXTENSION'
  ./sqlite3 -cmd 'pragma compile_options;' <<< .exit
cd -


# https://sqlite.org/src/dir?name=ext/icu
cd sqlite/ext/icu
  sed -i 's/int sqlite3_icu_init(/int sqlite3_extension_init(/' icu.c
  sed -i 's/int sqlite3IcuInit(/int sqlite3_extension_init(/' sqliteicu.h
  gcc -g -O2 -shared icu.c -fPIC -I ../../../build `pkg-config --libs icu-i18n` -o libSqlite3Icu.so
  cp libSqlite3Icu.so ../../../build/
cd -

# https://github.com/gwenn/sqlite-regex-replace-ext
cd sqlite/ext
  wget -O sqlite-regex-replace-ext-master.zip https://github.com/gwenn/sqlite-regex-replace-ext/archive/master.zip
  unzip   sqlite-regex-replace-ext-master.zip
  cd      sqlite-regex-replace-ext-master
    gcc -g -O2 -shared icu_replace.c -fPIC -I ../../../build -o libSqlite3IcuReplace.so
    cp libSqlite3IcuReplace.so ../../../build/
  cd -
cd ../../

结果,您将获得:
build/sqlite3              # sqlite3 binary
build/libSqlite3Icu.so     # unicode support
build/libSqlite3IcuReplace # regex_replace function

测试:
cd build
  sqlite3 <<< "
.load ./libSqlite3Icu
.load ./libSqlite3IcuReplace
select regex_replace('^a', 'aab', 'b');
.exit
  " # should output: bab
cd -

2

对我来说,上述答案并不适用,因为gcc命令中缺少一些参数。

这对我有用:

git clone https://github.com/gwenn/sqlite-regex-replace-ext.git
cd sqlite-regex-replace-ext-master/
./icu_replace.sh

现在您应该能够使用以下方式加载扩展程序:SELECT LOAD_EXTENSION('path-to-icu_replace.so');


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接