【问题标题】:replace a part of a string with REGEXP in sqlite3在 sqlite3 中用 REGEXP 替换字符串的一部分
【发布时间】:2016-12-17 02:24:33
【问题描述】:

我安装了 REGEX 支持

apt-get install sqlite3 sqlite3-pcre

现在我可以在 bash 控制台上的查询中使用 REGEX,例如

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 查询更新字符串?

【问题讨论】:

  • 你的意思是像 regexp_replace() ?
  • 是的。就这样。
  • 您能否接受这个答案,以便人们发现它对他们的情况有所帮助。

标签: regex sqlite pcre


【解决方案1】:

Sqlite 默认不提供 regex_replace 功能。您需要将其作为扩展加载。这是我设法做到的。

Download this C code for the extension (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() 函数似乎总是返回第二个参数。
  • @KevinRoth 嗨,kevin,抱歉打错了,这样使用 - select regex_replace('\bThe\b',x,'M') from dual;我也编辑了答案。
  • @Rubo Hi Rubo,您能否接受这个答案,以便对具有相同查询的其他用户有所帮助。
【解决方案2】:

以下构建支持动态库的最新sqlite,并编译ICU extensionregex_replace extension。它还假设基于 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 -

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 2022-07-18
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    相关资源
    最近更新 更多