Add Text replace using regex to placeholders

This commit is contained in:
Artem Chepurnoy 2024-01-06 18:04:56 +02:00
parent 6b6239f2fd
commit 89cc7ec047
No known key found for this signature in database
GPG Key ID: FAC37D0CF674043E
3 changed files with 54 additions and 1 deletions

View File

@ -0,0 +1,34 @@
package com.artemchep.keyguard.common.service.placeholder.impl
import com.artemchep.keyguard.common.io.IO
import com.artemchep.keyguard.common.io.ioEffect
import com.artemchep.keyguard.common.service.placeholder.Placeholder
import com.artemchep.keyguard.common.service.placeholder.util.Parser
class TextReplaceRegexPlaceholder(
) : Placeholder {
private val parser = Parser(
name = "t-replace-rx",
count = 3,
)
override fun get(
key: String,
): IO<String?>? {
val params = parser.parse(key)
?: return null
val regex = params.params.getOrNull(0)
val replacement = params.params.getOrNull(1)
if (
regex == null ||
replacement == null
) {
return null
}
return ioEffect {
val rg = regex.toRegex()
rg.replace(params.value, replacement)
}
}
}

View File

@ -73,6 +73,7 @@ import com.artemchep.keyguard.common.service.placeholder.impl.CommentPlaceholder
import com.artemchep.keyguard.common.service.placeholder.impl.CustomPlaceholder
import com.artemchep.keyguard.common.service.placeholder.impl.DateTimePlaceholder
import com.artemchep.keyguard.common.service.placeholder.impl.EnvironmentPlaceholder
import com.artemchep.keyguard.common.service.placeholder.impl.TextReplaceRegexPlaceholder
import com.artemchep.keyguard.common.service.placeholder.impl.TextTransformPlaceholder
import com.artemchep.keyguard.common.service.placeholder.impl.UrlPlaceholder
import com.artemchep.keyguard.common.service.placeholder.placeholderFormat
@ -474,6 +475,7 @@ fun vaultViewScreenState(
CommentPlaceholder(),
CustomPlaceholder(secretOrNull),
DateTimePlaceholder(),
TextReplaceRegexPlaceholder(),
TextTransformPlaceholder(),
EnvironmentPlaceholder(),
)

View File

@ -68,7 +68,24 @@ Note: `{base}` supports exactly the same parts as `{url}` and is identical to it
#### Text transformation
Convert text to the other representation.
##### Replace text using regular expression
```
t-replace-rx:/text/search/replace/
```
the first symbol after `:` defines the separator. It may be any symbol except `{` and `}`. Trailing separator symbol is required.
_Example_:
Let the username field contain the email address 'username@example.com', then:
```
> {t-replace-rx:/{username}/.*@(.*)/$1/}
example.com
```
for more info how it works, see the [underlying implementation's documentation](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/-regex/replace.html)
##### Convert text to the other representation
```
t-conv:/value/type/