Krishh
Krishh

Reputation: 33

regexp print line by line and remove last word

I am trying to remove last word from each line if line contains more than one word.

If line has only one word then print it as it, no need to delete it.

say below are the lines

address 34 address
value 1 value
valuedescription
size 4 size

from above lines I want to remove all last words from each line except from 3rd line as it has only one word using regexp ..

I tried below regexp and it is removing single word lines also

 $_ =~ s/\s*\S+\s*+$//; 

Need your help for the same.

Upvotes: 0

Views: 629

Answers (3)

Doug
Doug

Reputation: 709

a single word with no whitespace matches your regex since you've used \s* both before and after the \S+, and \s* matches an empty string.

You could use $_ =~ s/^(.*\S)\s+(\S+)$/$1/;

[Explanation: Match the RegEx if the line contains some number of characters ending with a non-whitespace (stored in $1), followed by 1 or more white-space characters, followed by 1 or more non-white-space characters. If there is a match, replace it all with the first part ($1).]

Though you might want to trim leading/trailing whitespace if you think it might contain any - depends on what you want to happen in those cases.

Upvotes: 0

anubhava
anubhava

Reputation: 785058

You can use:

$_ =~ s/(?<=\w)\h+\w+$//m; 

RegEx Demo

Explanation:

  • (?<=\w): Lookbehind to assert that we have at least one word char before last word
  • \h+: Match 1+ horizontal whitespaces
  • \w+: match a word with 1+ word characters
  • $: End of line

Upvotes: 4

Gurmanjot Singh
Gurmanjot Singh

Reputation: 10360

Try this regex:

^(?=(?:\w+ \w+)).*\K\b\w+

Replace each match with a blank string

Click for Demo

OR

^((?=(?:\w+ \w+)).*\b)\w+

and replace each match with \1

Click for Demo

Explanation(1st Regex):

  • ^ - asserts the start of the line
  • (?=(?:\w+ \w+)) - positive lookahead to check if the string has 2 words present in it
  • .* - If the above condition satisfies, then match 0+ occurrences of any character(except newline) until the end of the line
  • \K - forget everything matched so far
  • \b - backtrack to find the last word boundary
  • \w+ - matches the last word

Upvotes: 1

Related Questions