Vishal
Vishal

Reputation: 7361

Regex for checking the last character

How can I check if the last character of a string is ' ' or ','?

I know for checking last character of string we need use $, and I made this regex for checking that the last character is ',':

/\,$/

But I also need to check whether it's a space or not.

It will be very helpful if you give suggestion for making a regex like this.

Upvotes: 1

Views: 3837

Answers (3)

user9077625
user9077625

Reputation:

You can use a dot . to match any character except a new line. When you use the s flag, the dot can also match a new line.

/.$/s

Upvotes: 1

spickermann
spickermann

Reputation: 106802

Regexps don't come for free and are often much slower than using a simple method on String.

Therefore I would suggest to not use a regexp in thus case but String#end_with? instead:

string.end_with?(' ', ',')

IMHO it is also easier to read and to understand too.

Upvotes: 4

Igor Drozdov
Igor Drozdov

Reputation: 15045

You can use [] to provide a set of characters:

[,\s]\z

which means, that you want either , or space character at the end of the string

Upvotes: 2

Related Questions