Ashwin
Ashwin

Reputation: 1013

Tclsh: How to get the first occurence of the string by regexp?

I have a string with multiple occurring pattern. I need the extract the first pattern from the string.

i.e:

My Pattern:

ABC : 1
XXX : 3
YYY : 4
ZZZ : 9

ABC : 3
XXX : 4
YYY : 6
ZZZ : 7

I want to extract the block based on the value provided for ABC value. If I give ABC value as 1, output should be:

ABC : 1
XXX : 3
YYY : 4
ZZZ : 9

I tried,

set ABCVal 1

regexp "ABC\[ \]+:\[ \]+$ABCVal(.*)\[^ABC\]" $buffer

This matches the entire buffer.

Upvotes: 3

Views: 891

Answers (3)

Saran
Saran

Reputation: 366

Try this,

package require textutil
set new [textutil::splitx $buf {(?n)^\s*\n}]
set index [lsearch -regexp $new "ABC : $ABCVal"]
puts [lindex $new $index]

This will give the results as ABC : 3 XXX : 4 YYY : 6 ZZZ : 7

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 247210

I would first split the text into blank-line-separated units and then search that list for the pattern:

set text {ABC : 1
XXX : 3
YYY : 4
ZZZ : 9

ABC : 3
XXX : 4
YYY : 6
ZZZ : 7}
package require textutil::split
set blocks [textutil::split::splitx $text {\n{2,}}]
set abc 3
set index [lsearch -regexp $blocks "^ABC : $abc\\y"]
puts [lindex $blocks $index]
ABC : 3
XXX : 4
YYY : 6
ZZZ : 7

I use the regexp \y assertion so "^ABC : 3" does not match the text "ABC : 345"

Upvotes: 2

Ωmega
Ωmega

Reputation: 43703

if {[regexp "(?p)^ABC : $ABCval(?=\n).*?(?=\n\n|$(?!.))" $input]} { ...

Upvotes: 0

Related Questions