mixing pattern and exact matches in Tcl

Viewed 40

I am trying to search for different things in a string. For example, I am ready a file and parsing it all the way through. Then I match few strings in each line. The String in question could be a pattern match or exact match, how can I accomplish it in a single statement?

This is what I am trying to do:

set $string = " My name is Peter Gabriel Perlston and I live in Gabriel_Perlston town"

set match [regexp -all -inline {Pet|"Perlston"} $string]

Now what I want is that every time it matches a pattern Pet, it prints something OR if it matches Perlston exactly with nothing around like _..Just that word..it print something.

I can do it in multiple statements but I was hoping if there is a one liner that I can use? I want to make this a generic statement so in future if there is another string or exact name, I can add to $string and be done with it.

1 Answers

It sounds like you want to use a regex with alternatives with the | character.

In the below code, the Pet will find any match of Pet anywhere, and \mPerlston\M uses the word boundary start and end markers before and after Perlson.

set match [regexp -all -inline {Pet|\mPerlston\M} $string]

Related