I want to run a query in SQLite with a regexp using Android.
How do I do that?
3 Answers
Unfortunately it doesn't look like Android currently supplies a way for you to inject a user function into sqlite, which is what you'd need to make REGEXP work (specifically, you'd need a user function named regexp()) -- so you may have to select more broadly (with a LIKE condition that's broader than the regexp you want) and further distinguish "actual" result (those that really match the regexp you want) with java.util.regex in your application.
Comments
Very late to the party here, but you can use REGEXP in Room - you just have to enable it first. Firstly, in your @Dao interface, set up a @RawQuery function (in Kotlin):
@Dao
interface WordsDao {
@RawQuery
fun getMatches(query: SimpleSQLiteQuery): List<Word>
@RawQuery
fun enableRegexp(query: SimpleSQLiteQuery): Boolean
}
Then you need to call it with the query to enable REGEXP:
private fun enableRegexp() {
Single.fromCallable {
appDB?.wordsDao()?.enableRegexp(SimpleSQLiteQuery("PRAGMA compile_options='ENABLE_REGEXP'"))
}.doOnSuccess {
Log.d("REGEXP", "Success")
}.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe()
}
Now you can run a SELECT query on the database using regex:
appDB?.wordsDao()?.getMatches(SimpleSQLiteQuery("SELECT * FROM words_alpha WHERE word REGEXP '^[olgf]{4}+\$'"))
4 Comments
REGEXP support, and PRAGMA compile_options can't enable it since it's not compiled into Android's SQLite binary. The ENABLE_REGEXP pragma you're trying to use is something that's available in some SQLite builds, but not in Android's default SQLite implementation. How and where did you make yours work?Patterns are compiled regular expressions. In many cases, convenience methods such as String.matches, String.replaceAll and String.split will be preferable, but if you need to do a lot of work with the same regular expression, it may be more efficient to compile it once and reuse it. The Pattern class and its companion, Matcher, also offer more functionality than the small amount exposed by String.
http://developer.android.com/reference/java/util/regex/Pattern.html