1

I'm using Rails 5. I want to replace occurrences in a string of an arbitrary amount of numbers, an optional number of spaces, a token from an array of strings, an optinal number of spaces, and an arbitrary amount of numbers. So for example, this would match my pattern ....

123 / 2221111

or this

 102849/222

so I thought my regular expression should be

re = /\d+[[:space:]]*[#{Regexp.union(TOKENS)}][[:space:]]*\d+/

but the following is matching something that does not fit the criteria ...

2.4.0 :015 > re = /\d+[[:space:]]*[#{Regexp.union(TOKENS)}][[:space:]]*\d+/
 => /\d+[[:space:]]*[(?-mix:of|\/)][[:space:]]*\d+/
2.4.0 :016 > TOKENS
 => ["of", "/"]
2.4.0 :017 > name = "10F 2017"
 => "10F 2017"
2.4.0 :018 > name.gsub!(re, '#')
 => "#"

The string "10F 2017" does not contain any of the strings from my TOKENS array so right there things should fail. How do I rewrite my regex so that it only matches what I want?

1
  • Dave, [(?-mix:of|\/)] matches a single char: (, a range from ? to m (i.e. a lot of letters, all ASCII uppercase ones), i. etc. Delete the [ and ]. Commented Aug 11, 2017 at 18:15

1 Answer 1

2

By enclosing the #{Regexp.union(TOKENS)} into a character class, [(?-mix:of|\/)], you made it match a single char: (, characters ranging from ? to m, i, etc. The range between ? and m matches:

enter image description here

And see what parts of the string each part of your regex matches:

enter image description here

So, [(?-mix:of|\/)] matched F in your input string.

You need to remove [ and ]:

re = /\d+[[:space:]]*#{Regexp.union(TOKENS)}[[:space:]]*\d+/

See the Ruby demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.