Mont
Mont

Reputation: 311

Ruby Regex and string variable

I am trying to match a string with a non-breaking space ( ) given a variable that contains the string with a regular space. The string I am looking for is the text in a HTML link/anchor and I am using Watir (note the non-breaking space).

<a onlick='DoSomthing()' href=''>Some&nbsp;Text</a>

There appears to be a difference between a regex created by // and by Regex.new.

Interactive Ruby says the following is true (where my_text = 'Some Text'):

/Some Text/ == Regexp.new(my_text)

Yet while this returns True:

browser.link(:text, /Some Text/).exists?

This does not:

browser.link(:text, Regexp.new(my_text)).exists?

Nor does this:

browser.link(:text, /#{my_text}/).exists?

I've also tried the following with no luck:

Regexp.new(my_text.gsub(' ', '[[:space:]]'))

Does anyone know how I can accomplish this match?

Upvotes: 2

Views: 1204

Answers (2)

Andrew Cheong
Andrew Cheong

Reputation: 30273

Use alternation:

browser.link(:text, / |&nbsp;/).exists?

Also, try upgrading Ruby and gems. I've heard weird regex issues in Watir resolving magically that way.

Upvotes: 1

DGM
DGM

Reputation: 26979

A non breaking space is an html entity, and regex afaik does not recognize that as a space, so you need to convert one or the other before matching.

my_text = 'Some&nbsp;Text'

in other words, I don't think regex would ever match a space to "&nbsp;". change your search string, or the source text, whichever is easier...

Upvotes: 1

Related Questions