How to match the nth occurrence in a string using a regex

How to match the nth occurrence in a string using a regular expression

set test {stackoverflowa - the best site for finding solutions stackoverflowb - the best solution for searching. stackoverflowc is the best solution for finding sitestackoverflowd is the best solution sitestackoverflowe is the best site for finding solutions}

regexp -all {stackoverflow} $test 

The above gives "5" as output

regexp {stackoverflow} $test 

In the above example, the result is stackoverflow, here it matches the first occurrence of stackoverflow (ie) stackoverflowa

My requirement is I want to match the 5th occurrence of stackoverflow (ie) stackoverflowe from the line above.

Please clarify my question ... Thank you

Then another question

+4
source share
1 answer

Try

set results [regexp -inline -all {stackoverflow.} $test]
# => stackoverflowa stackoverflowb stackoverflowc stackoverflowd stackoverflowe
puts [lindex $results 4]

I'll be back to explain it further by making pancakes right now.

So.

The command returns a list ( -inline) of all ( -all) substrings of the string contained in testthat matches the string "stackoverflow" (fewer quotation marks) plus one character, which can be any character. This list is stored in a variable resultand by indexing with 4 (since indexing is based on zero), the fifth element of this list can be retrieved (and in this case printed).

: , , . , , , "stackoverflow" .

ETA ( ): , . -indices ( : , "stackoverflow" ):

set indices [regexp -inline -all -indices {stackoverflow} $test]
# => {0 12} {47 59} {94 106} {140 152} {186 198}

string range, :

puts [string range $test {*}[lindex $indices 4]]

lindex $indices 4 186 198; {*} string range.

+3

Source: https://habr.com/ru/post/1523396/


All Articles