meow
meow

Reputation: 28164

Regular expression - excluding a character

Here is an example:

s="[email protected]"

s.match(/+[^@]*/)

Result => "+subtext"

The thing is, i do not want to include "+" in there. I want the result to be "subtext", without the +

Upvotes: 6

Views: 6629

Answers (4)

Wayne Conrad
Wayne Conrad

Reputation: 107969

You can use parentheses in the regular expression to create a match group:

s="[email protected]"
s =~ /\+([^@]*)/ && $1
=> "subtext"

Upvotes: 6

Jason Miesionczek
Jason Miesionczek

Reputation: 14448

This works for me:

\+([^@]+)

I like to use Rubular for playing around with regular expressions. Makes debugging a lot easier.

Upvotes: 2

dawg
dawg

Reputation: 103744

I don't know Ruby very well, but if you add capturing around the portion you want it should work. ie: \+([^@]*)

You can test these with Rubular. This specific match is here: http://www.rubular.com/r/pqFza9jlmX

Upvotes: 1

David Z
David Z

Reputation: 131550

You could use a positive lookbehind assertion, which I believe is written like this:

s.match(/(?<=\+)[^@]*/)

EDIT: So I just noticed this is a Ruby question, and I don't know if this feature is in Ruby (I'm not a Ruby programmer myself). If it is, you can use it; if not... I'll delete this.

Upvotes: 2

Related Questions