Need some help with regexp

Hello, I need some help with regex
I have the following expression: “Laptop MARCOCHEN (192.168.5.73)”
I need a regular express to capture only the second word, in this case
“MARCOCHEN”. I don’t want to use “split”

So far I am using / \S+ /i
but this is getting also the spaces before and after so what I am
getting is " MARCOCHEN "

Any advice?

Thanks a lot!

You are getting that because you have spaces in it. You can get the same
result if you use /(\S+)/ and using the $1 variable, which should
contain
“MARCOCHEN”.

On Sun, Oct 2, 2011 at 11:46 AM, Eyal Eizenberg
<[email protected]

wrote:

Thanks a lot!


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


Sincerely,

Isaac S.
Section C-4B Vice Chief, Order of the Arrow
Vice Chief of Administration, Tecumseh #65
Eagle Scout

Is there a way to do it so that the $& will contain “MARCOCHEN”?

Isaac S. wrote in post #1024664:

You are getting that because you have spaces in it. You can get the same
result if you use /(\S+)/ and using the $1 variable, which should
contain
“MARCOCHEN”.

Eyal Eizenberg wrote in post #1024722:

Is there a way to do it so that the $& will contain “MARCOCHEN”?

Base on your pattern, /(?<= )\S+(?= )/i will work.

On Mon, Oct 3, 2011 at 9:06 AM, Eyal Eizenberg
[email protected] wrote:

Is there a way to do it so that the $& will contain “MARCOCHEN”?

Isaac S. wrote in post #1024664:

You are getting that because you have spaces in it. You can get the same
result if you use /(\S+)/ and using the $1 variable, which should
contain
“MARCOCHEN”.

Even better - you don’t need $&:

irb(main):001:0> s=“Laptop MARCOCHEN (192.168.5.73)”
=> “Laptop MARCOCHEN (192.168.5.73)”
irb(main):002:0> s[/\A\s*\w+\s+(\w+)/, 1]
=> “MARCOCHEN”

or

irb(main):005:0> s[/\A\s*\S+\s+(\w+)/, 1]
=> “MARCOCHEN”

Kind regards

robert

$~ has the matched result from the most recent regexp. Convert to a
string thusly

($~).to_s

Joe

Sent from my iPad

Please do not top post.

On Mon, Oct 3, 2011 at 6:42 PM, [email protected]
[email protected] wrote:

$~ has the matched result from the most recent regexp. Convert to a string
thusly

($~).to_s

You’re point being? Why would I bother to use $~.to_s if I can
directly use $& and get the same? Also, my point was specifically
that you can get away without those global variables and instead use
what String#[] returns.

Joe

Sent from my iPad

Maybe you had better used a real computer.

Cheers

robert

$& works fine also

Joe

Sent from my iPad

I have a real computer but not always access to it

Joe

Sent from my iPad

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