Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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?

share|improve this question
    
If you create a page that just has that one link, do the above attempts work? They worked for me when I tried them (while using watir-webdriver with Firefox). – Justin Ko Jul 12 '13 at 20:15
up vote 1 down vote accepted

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.

share|improve this answer
    
I've just discovered that the issue apparently has nothing to do with Regex. The problem is somehow rooted in passing a string constant to a method. I am going to post that issue separately. Thanks for the suggestion. – Mont Jul 12 '13 at 22:20
    
As best I can tell this was a glitch in the IDE (RubyMotion). The exact same code I was using before is now producing different results. While Regex/Watir are matching fine with just a regular space (now) I am marking this as the answer as swapping spaces for '( |&nbsp;)' seems more robust. – Mont Jul 15 '13 at 15:28

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...

share|improve this answer
    
I had seen elsewhere that [[:space:]] would work. I don't know if it should/shouldn't. The crazy thing is that /Some Text/ works just fine but as soon as I stick "Some Text" in a variable it refuses to work. – Mont Jul 12 '13 at 22:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.