I know you can find a string and place everything after it into a variable using TCL and regex like the following
regexp "Shipping \(\[^\f]+)" $VarWithWholePage match shipinfo;
But is it possible to place everything before the string into a variable?
For example.
Sentence number 1.
Sentence number 2.
Sentence number 3.
Sentence number 4.
Shipping
Sentence number 5.
My example would place "Sentence number 5." into shipinfo
, but I would like to be able to place
Sentence number 1.
Sentence number 2.
Sentence number 3.
Sentence number 4.
into another variable.
regexp "\(.*\)Shipping \(\[^\f]+)" $VarWithWholePage match before after;
should put the text before "Shipping" in before
and the part after in after
.
PS I am not sure why you are using ^\\f
, but if you have a good reason you can use it also in the first subexpression.
But is it possible to place everything before the string into a variable?
The simplest way to do this is to get regexp
to tell you the indices of the match instead of the matched substring. You can then use string range
to get the parts you want.
regexp -indices "Shipping \(\[^\f]+)" $VarWithWholePage match shipinfo
At this point, match
and shipinfo
will have pairs of numbers indicating exactly where the match happened within the input string. If the match succeeded.
# Now we can get the bits before (and after) the match with simple operations
set beforeMatch [string range $VarWithWholePage 0 [expr {[lindex $match 0] - 1}]]
set afterMatch [string range $VarWithWholePage [expr {[lindex $match 1] + 1}] end]
# Convert the string ranges into the matched substrings so that your code still works
set match [string range $VarWithWholePage {*}$match]
set shipinfo [string range $VarWithWholePage {*}$shipinfo]
Footnote: your RE would be idiomatically written as {Shipping ([^\\f]+)}
as it's usually a very good idea to put regular expressions in braces. It combats backslash-itis.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.