Vikrant Chaudhary
Vikrant Chaudhary

Reputation: 11289

Regular expression for not matching two underscores

I don't know whether it's really easy and I'm out of my mind....

In Ruby's regular expressions, how to match strings which do not contain two consecutive underscores, i.e., "__".

Ex:

Matches: "abcd", "ab_cd", "a_b_cd", "%*##_@+"
Does not match: "ab__cd", "a_b__cd"

-thanks

EDIT: I can't use reverse logic, i.e., checking for "__" strings and excluding them, since need to use with Ruby on Rails "validates_format_of()" which expects a regular expression with which it will match.

Upvotes: 2

Views: 4954

Answers (4)

Amarghosh
Amarghosh

Reputation: 59451

Negative lookahead

\b(?!\w*__\w*)\w+\b

Search for two consecutive underscores in the next word from the beginning of the word, and match that word if it is not found.

Edit: To accommodate anything other than whitespaces in the match:

(?!\S*__\S*)\S+

If you wish to accommodate a subset of symbols, you can write something like the following, but then it will match _cd from a_b__cd among other things.

(?![a-zA-Z0-9_%*#@+]*__[a-zA-Z0-9_%*#@+]*)[a-zA-Z0-9_%*#@+]+

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838246

/^([^_]*(_[^_])?)*_?$/

Tests:

regex=/^([^_]*(_[^_])?)*_?$/

# Matches    
puts "abcd" =~ regex
puts "ab_cd" =~ regex
puts "a_b_cd" =~ regex
puts "%*##_@+" =~ regex
puts "_" =~ regex
puts "_a_" =~ regex

# Non-matches
puts "__" =~ regex
puts "ab__cd" =~ regex
puts "a_b__cd" =~ regex

But regex is overkill for this task. A simple string test is much easier:

puts ('a_b'['__'])

Upvotes: 4

user222229
user222229

Reputation:

Would altering your logic still be valid?

You could check if the string contains two underscores with the regular expression [_]{2} and then just ignore it?

Upvotes: 2

Andomar
Andomar

Reputation: 238086

You could use negative lookahead:

^((?!__).)*$

The beginning-of-string ^ and end of string $ are important, they force a check of "not followed by double underscore" on every position.

Upvotes: 12

Related Questions