Regex ignore whitespace in target string

Hi,

Does anyone know how to ignore whitespace in the target string (Not in
the expression itself, which is what I believe /x does)?

eg question.match(/{(male|female),[0-99][0-99]%}/)

“{male/female,50%}” vs # “{male/female, 50%}”

Thanks,
Dave

Just remove all the whitespace before you match.
question.gsub(/\s+/, ‘’).match …

On Feb 2, 2014, at 1:34 PM, Dave C. [email protected]
wrote:

Dave


Posted via http://www.ruby-forum.com/.

You can use \s* to match 0 or more “whitespace” characters, for example

/{ # opening {
((?:fe)?male) # male or female stored into $1
, # a comma
\s* # zero or more spaces
0*?(100|[1-9]\d|\d)% # soak up leading 0s and then have a valid
percentage (0 - 100) -> $2
% # then an %
} # then a closing }
/x

might do what you want. You can play with it at
http://rubular.com/r/ASK9yMubOH to see if it does

Hope this helps,

Mike

Mike S. [email protected]
http://www.stok.ca/~mike/

The “`Stok’ disclaimers” apply.

On Sun, Feb 2, 2014 at 7:34 PM, Dave C. [email protected]
wrote:

Hi,

Does anyone know how to ignore whitespace in the target string (Not in
the expression itself, which is what I believe /x does)?

eg question.match(/{(male|female),[0-99][0-99]%}/)

You want “/” rather than “|” between “male” and “female” to match the
given strings.

“{male/female,50%}” vs # “{male/female, 50%}”

As Mike said, you can use \s* to match arbitrary sequences of
whitespace (including the empty one).

irb(main):005:0>
“{male/female,50%}”.match(/{(male/female),\s*[0-99][0-99]%}/)
=> #<MatchData “{male/female,50%}” 1:“male/female”>
irb(main):006:0> “{male/female,
50%}”.match(/{(male/female),\s*[0-99][0-99]%}/)
=> #<MatchData “{male/female, 50%}” 1:“male/female”>

I just notice you have a duplicate 9 in the character class. And you
do not need to escape %. You probably rather want:

/{(male/female),\s*\d{1,2}%}/

Kind regards

robert

Thanks!

  • very helpful.

Dave

On Feb 2, 2014, at 2:30 PM, Mike S. [email protected] wrote:

, # a comma
\s* # zero or more spaces
0*?(100|[1-9]\d|\d)% # soak up leading 0s and then have a valid percentage
(0 - 100) -> $2

There shouldn’t be a % in the line above and the line below, I made a
mistake while adding comments!

Mike S. [email protected]
http://www.stok.ca/~mike/

The “`Stok’ disclaimers” apply.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs