So I apparently suck at regexes. I'm trying to co...
# random
c
So I apparently suck at regexes. I'm trying to come with the simplest regex based alternative (due to a spec out of my control) to
substringAfter()
What would the kotlin regex based alternative to
substringAfter("abc")
be for example?
e
I think
.*abc(.*)
and then get the first group
This should do it:
Copy code
val match = Regex(".*abc(.*)").find("<your string here>")
if(match != null && match.groupValues.size >= 2) {
  match.groupValues[1]
}
g
I would use
(?<=abc).*
for substring after
abc
. (At least on JVM.) UPD. It works on JS, as well.
k
Using positive lookbehind, as Gleb suggested:
Copy code
fun String.reinventedSubstringAfter(delimiter: String) =
    "(?<=$delimiter).*".toRegex().find(this)?.value ?: this
(assuming the delimiter doesn't contain any special characters). You might want to drop the
?: this
at the end, if you want it to return null if it doesn't find the substring. I put it in there to make it compatible with the standard
substringAfter
which returns the original string.
👍 1
c
FWIW This was the closest I could get
Copy code
fun findThing(chars: String, line: String): String? {
    val matcher = Pattern.compile(".*$chars(.*)").matcher(line)
    if (matcher.matches()) {
      return matcher.group(1)
    }
    return null
  }
but let me try the examples you all gave. Was hoping for a one-liner really, but doesn't seem like it. lol
oh actually @Klitos Kyriacou seems like a decent one liner
h
This is a brilliant tool: https://regex101.com/ − but it does lack the ability to say «listen, your regex is OK, but here's a more efficient one (or a more readable one): ---»
a
You're not the only one that suck with regex, in my case I use ChatGPT to generate the regex and test the result using regex101 😅
👆 1
c
I feel like I can sometimes get a regex together, but the regex apis always mess me up. It seems like theres so many ways for a regex and matchers. just makes my head hurt.