I want to find index from string. How can i find t...
# android
v
I want to find index from string. How can i find the index of the first alphabet of second last word in a string.
Copy code
val index = "Hey! How are you men? How you doing"
i want to search you doing from the above string, but i want y index from the word you. I did some code to find index but I am unable to find it.
Copy code
fun main(vararg args: String) {
    val inputString = "Hey! How are you men? How you doing"
    val regex = "you doing".toRegex()
    val match = regex.find(inputString)!!
    println(match.value)
    println(match.range)
}
l
Your example works. Are you looking for a more generic regex?
v
yes more generic
I am getting the string randomly. I always want to find the index of the first alphabet of second last word in a string without match string.
l
I got
"(?<= )\\w+ \\w+\\z"
which works with your example, but it matches words with numbers and underscore as well
v
can you please explain @Luke
l
If you only want letters, replace both
\\w
with
[a-zA-Z]
Yes,
(?<= )
, matches a space, but will not be part of the resulting match. It just looks that the preceding character is a space
\\w
matches a letter (caps or not), a number or an underscore. The
+
after means there can be more than one
v
cool thanks a lot @Luke
l
The space matches a space of course, and
\\z
matches the end of a string
t
Untitled
Do you want the range of where the string is, or just the start index of the substring? If you just want the start index, I’d avoid regex and use the indexOf extension.
v
i want start index
thanks men
👍 1