2

Is there a way to create a regex for initials without using back references? For example, say I want initials for

New.York

And the regex to output

N.Y. (or n.y)

So far I have the following:

.\.[a-zA-Z]+

This outputs the last the initial of the first word instead of the first initial: w.y.

UPDATE**

I'm also assigned the RegExp to variable and using the =~ to test some things.

user3465296
  • 143
  • 1
  • 12
  • 1
    Is there a reason you can't do a replace (just replace all lower-case letters), instead of a match? – elixenide Sep 10 '14 at 14:08
  • I'm assigning the RegExp to a variable also – user3465296 Sep 10 '14 at 14:21
  • 1
    Why a regex? Seems like splitting and grabbing first letters might be easier. – Dave Newton Sep 10 '14 at 14:53
  • 2
    @user3465296 Okay, but again, what is your desired outcome? Why can't you use back-references? In short, what's the point? Do you just want to validate a format? Do you just want to get the string "N.Y."? What do you need, really? – elixenide Sep 10 '14 at 15:07

4 Answers4

3

You could remove all the lowercase letters using gsub function,

irb(main):004:0> str = "New.York"
=> "New.York"
irb(main):006:0> str.gsub(/[a-z]+/, "")
=> "N.Y"
Avinash Raj
  • 160,498
  • 22
  • 182
  • 229
1

A ruby way to do this given your input of "New.York" could be:

str.split('.').collect { |s| s[0] }.join('.')

which would return 'N.Y'

spig
  • 1,577
  • 6
  • 20
  • 29
0

Use this regex and you should only output the groups \1 and \2.

([a-zA-Z])[^.]*\.([a-zA-Z]).*?\b

DEMO

If you want to do a replacement you should use \1.\2

Oscar Hermosilla
  • 421
  • 5
  • 20
0

You could use the capital letters to dictate the regex match using something like this:

[15] pry(main)> str
=> "New.York"
[16] pry(main)> str.scan(/[A-Z]+/).join('.')
=> "N.Y"
Anthony
  • 14,060
  • 3
  • 32
  • 61