From: Ross Bamford Date: 2006-03-10T20:50:16+09:00 Subject: Re: Small regexp question On Fri, 2006-03-10 at 19:58 +0900, francisrammeloo@hotmail.com wrote: > Hi all, > > I am writing some refactoring code for a C++ project. > > I need to change: > > class MyClass > { > ... > } > > to: > > class IMP_EXP MyClass > { > ... > } > > The pattern I used to find a class definition line is: > > line =~ /^\s*class\s+(\w+)/ > > But I want to exclude forward class declarations ( class MyClass; ) > > So I changed my pattern to: > > line =~ /^\s*class\s+(\w+)\s*[^;]/ --> don't match if line ends > with ";" > > But it doesn't work... Why? Your regexp is trying to match: + zero or more spaces + the word 'class' + one or more spaces + one or more word characters (captured) + zero or more spaces + any single character except ';' By the time you get to that ';' there likely won't be any input left, so no character to be something except ';'. You could do it with lookahead, but it's probably easier to do: "class MyClass;" =~ /class\s+(\w+)[^;]*$/ # => nil "class MyClass" =~ /class\s+(\w+)[^;]*$/ # => 0 "class MyClass {" =~ /class\s+(\w+)[^;]*$/ # => 0 "class MyClass { /* etc */ }" =~ /class\s+(\w+)[^;]*$/ # => 0 There are probably still things this will miss though. For example, strange class names could well result in a failure to match... -- Ross Bamford - rosco@roscopeco.REMOVE.co.uk