regular expression to remove the first word of each line

I am trying to make a regular expression that grabs the first word (including possible leading white space) of each line. Here it is:

/^([\s]+[\S]*).*$/\1//

This code does not seem to be working (see http://regexr.com?34o6m). The code is supposed to

  1. Begin at the start of the line
  2. Create a capturing group where it places the first word (with possible leading white space)
  3. Grab the rest of the line
  4. Substitute the entire line with just the inside of the first capturing group

I tried another version also:

/\S(?<=\s).*^//

It looks like this one fails too (http://regexr.com?34o6s). The goal here was to

  1. Find the first non-whitespace character.
  2. Look behind to make sure it has a whitespace character behind it (i.e. not the first letter of the line).
  3. Grab the rest of the line.
  4. Erase everything the expression just grabbed.

Any insight to what is going wrong would be greatly appreciated. Thanks!

Answers


You mixed up your + and *.

/^([\s]*[\S]+).*$/\1/

This means zero or more spaces followed by one or more non-spaces.

You might also want to use $1 instead of \1:

/^([\s]*[\S]+).*$/$1/

Okay, well this seems to work using replace() in Javascript:

/^([\s]*[\S]+).*$/

I tested it on www.altastic.com/regexinator, which as far as I know is accurate [I made it though, so it may not be ;-) ]


Try this regular expression

^(\s*.*?\s).*

Demo: gskinner


Need Your Help

C++ function template partial specialization?

c++ templates template-specialization partial-specialization

I know that the below code is a partial specialization of a class:

Android: Attempting to Instantiate a class

java android instantiation

I am still new to Java programming in general and I'm now trying to tackle instantiating, and encountering some problems. I have tried to make as simple as possible way to test this, however my pro...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.