aressidi
aressidi

Reputation: 680

ruby regex need to match only if a URL is found in a string once

I'm trying to add conditional logic to determine if there's one regex match for a URL in a string. Here's an example of the string:

string_to_match = "http://www.twitpic.com/23456 ran to catch the bus, http://www.twitpic.com/3456 dodged a bullet at work."

I only want to match if I determine there's one URL in the string, so the above string wouldn't be a match in the case I'm trying to solve. I thought something like this would work:

if string_to_match =~  /[http\:\/\/]?/
   puts "you're matching more then once. bad man!"
end

But it doesn't! How do I determine that there's only one match in a string?

Upvotes: 0

Views: 612

Answers (3)

FMc
FMc

Reputation: 42411

The answer from Mladen is fine (counting the return from scan), but regular expressions already include the idea of matching the same thing multiple times or a particular number of times. In your case, you want to print the warning if your text occurs 2 or more times:

/(http:\/\/.+?){2,}/

Use .+ or .*, depending on whether you want to require the URL to have some content or not. As it stands, the .+? will match 1 or more characters in a non-greedy fashion, which is what you want. A greedy quantifier would gobble up the entire string on the first try and then have to do a bunch of backtracking before ultimately finding multiple URLs.

Upvotes: 2

Mladen Jablanović
Mladen Jablanović

Reputation: 44080

Take a look at String#scan, you can use it this way:

if string_to_match.scan(/[http\:\/\/]/).count > 1
   puts "you're matching more then once. bad man!"
end

Upvotes: 1

ennuikiller
ennuikiller

Reputation: 46965

you could do it like this:

if string_to_match =~ /((http:\/\/.*?)http:\/\/)+/

this would match only if you have 2 (or more) occurrences of http://

Upvotes: 1

Related Questions