Reputation: 33
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
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
Reputation: 785058
You can use:
$_ =~ s/(?<=\w)\h+\w+$//m;
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 lineUpvotes: 4
Reputation: 10360
Try this regex:
^(?=(?:\w+ \w+)).*\K\b\w+
Replace each match with a blank string
OR
^((?=(?:\w+ \w+)).*\b)\w+
and replace each match with \1
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 wordUpvotes: 1