2

I need a regex that will match everything before a last dot in my string. For example, I have text like this: if_blk4.if_blk1.if_blk1 I would like to get the if_blk4.if_blk1.

Thanks!

Sasa Stamenkovic
  • 85
  • 1
  • 2
  • 9
  • 3
    `(.*)\.` Then get the result for matching group 1, e.g. $1 or \1 depending on the regex dialect. – Andy Aug 26 '16 at 18:44
  • This is a basic regex. What did you try? If you don't know the regex then [here](http://stackoverflow.com/questions/4736/learning-regular-expressions) is a good place to start. – Dave Grabowski Aug 26 '16 at 18:47
  • Dupe of http://stackoverflow.com/questions/36801188/simple-regex-match-everything-until-the-last-dot/36801287 – Wiktor Stribiżew Aug 26 '16 at 19:17

2 Answers2

10

To match everything up to (but not including) the last dot, use a look ahead for a dot:

.*(?=\.)

The greedy quantifier * makes the match include as of the input much as possible, while the look ahead (?=\.) requires the next character in the input to be a dot.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

How about

regexp {.*(?=\.[^.]*$)} $text match

i.e. matching any characters that lead up to a (not matched) sequence of dot and zero or more characters that aren't dots, followed by the end of the string.

(The regular expression {.*(?=\.)} is equivalent as regular expression matching doesn't need to be anchored.)

or (faster)

file rootname $text

Documentation: file, regexp, Syntax of Tcl regular expressions

Peter Lewerin
  • 13,140
  • 1
  • 24
  • 27
  • Looking up from my own code, Andy's `(.*)\.` is much more elegant, with only the small disadvantage that one must use a capture group. But the `file rootname` variant is best. – Peter Lewerin Aug 26 '16 at 18:55