Home > Mobile >  Removing last character from a line using regex
Removing last character from a line using regex

Time:08-15

I just started learning regex and I'm trying to understand how it possible to do the following:

If I have:

helmut_rankl:20Suzuki12
helmut1195:wasserfall1974
helmut1951:roller11

Get:

helmut_rankl:20Suzuki1
helmut1195:wasserfall197
helmut1951:roller1

I tried using .$ which actually match the last character of a string, but it doesn't match letters and numbers.

How do I get these results from the input?

CodePudding user response:

You could match the whole line, and assert a single char to the right if you want to match at least a single character.

. (?=.)

Regex demo

If you also want to match empty strings:

.*(?=.)

CodePudding user response:

This will do what you want with regex's match function.

^(.*).$

Broken down:

^ matches the start of the string

( and ) denote a capturing group. The matches which fall within it are returned.

.* matches everything, as much as it can.

The final . matches any single character (i.e. the last character of the line)

$ matches the end of the line/input

  • Related