elju
elju

Reputation: 435

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!

Upvotes: 1

Views: 19108

Answers (4)

wharton323
wharton323

Reputation: 1

remove the first two words @"^.asterisk? .asterisk? " this works for me

when posted, the asterisk sign doesn't show. have no idea.

if you want to remove the first word, simply start the regex as follow a dot sign an asterisk sign a question mark a space replace with ""

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388436

Try this regular expression

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

Demo: gskinner

Upvotes: 3

David John Welsh
David John Welsh

Reputation: 1569

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 ;-) ]

Upvotes: 1

paddy
paddy

Reputation: 63481

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/

Upvotes: 1

Related Questions