Why this regular expression matches /\w+[^(]/? - ruby

>> 'hola(' =~ /\w+[^(]/
=> 0
>> $&
=> "hola"
As far as I know, /\w+[^(]/ should match a word not followed by a (. I also tried with negative look-behind and escaping the (; with the same results.
What I find estrange about this, is that if I try with /a[^(]/, it works (as expected).
>> 'hola(' =~ /a[^(]/
=> nil
So it definitely has something to do with the + quantifier.
What's happening?
I tried using Ruby 2.2 and Python 3.3

The hol portion matches the \w+ portion of the expression, and the [^(] portion matches a. The ( part of the input is ignored.
Add $ to fix the problem:
>> 'hola(' =~ /\w+[^(]$/
=> nil

In this example, the regex engine works like this: scan down to hola which matches \w+ part, but the next character ( doesn't match [^(], then does backtracking, and find out that it matches when hol to \w+ part, and a matches [^(] part.
You can inhibit the backtracking by using (?>re) for an independent regex engine:
'hola(' =~ /(?>\w+)[^(]/
# => nil
or ++ repetition for possessive:
'hola(' =~ /\w++[^(]/
# => nil
Both are Ruby Regexp extensions.

Actually \w+[^(] matches one or more word-characters, followed by any character that isn't a (.
Which means it will match hola and ignore the last character.
Depending on where you want to use this, a pattern like \w+\b(?!\() might be more suitable, as it will match any word not followed by (.

Related

Simple repetition in Ruby regexp not working

I'm trying to figure out why Ruby's repetition for pattern matching isn't returning what I think it should.
Here's the simplest version of my problem:
str="Hello"
# Matches "Hello" correctly
pattern1=/[A-Z][a-z]*/
r = pattern1.match(str)
puts("[#{r}]")
# prints "[Hello]"
# Matches "e" correctly
pattern2=/[a-z]/
r = pattern2.match(str)
puts("[#{r}]")
# prints "[e]"
# Should match "ello" but doesn't
pattern3=/[a-z]*/
r = pattern3.match(str)
puts("[#{r}]")
# prints "[]"
According to the docs, the * match should be greedy. It doesn't seem to be. What am I doing wrong?
For what it's worth, grep (and PHP) seem to behave as expected:
$ echo "Hello" | grep "[A-Z][a-z]*"
Hello
I'm using ruby 2.6.5p114 if that helps.
Reason for this behaviour is that /[a-z]*/ matches the character group [a-z] zero or more times. The .match method matches the first thing it can find.
/[a-z]*/.match("Hello")
Will thus match before the "H" since it matches the criteria of a length of zero [a-z] characters. The second match would be "ello".
"Hello".scan(/[a-z]*/) #=> ["", "ello", ""]
You might want to use the + quantifier to match one or more times.

Why does my regexp not tell me if a string contains no numbers?

I'm using Ruby 2.4. How do I check if a string doesn't contain any numbers? I'm trying this
2.4.0 :002 > line = "abcdef"
=> "abcdef"
2.4.0 :007 > line =~ /^^[0-9]+$/
=> nil
I thought the "^" was the "not" character, but I'm not sure how it works because I know it is also the phrase starting character. Anyway, help is appreciated, -
^ negates a set of characters when at the beginning of the square-bracketed list:
[^abc] # not a, b, or c
so you just need to move it inside the brackets:
line =~ /^[^0-9]+$/
Note that you probably want \A and \z instead of ^ and $, since they match the starts and ends of entire strings instead of lines, and that \D is short for [^0-9].
line =~ /\A\D+\z/
You can also do a negative check for digits.
line !~ /\d/
You can use match? like this:
'abcdef'.match?(/\d/)
#=> false

Regex to find strings with only letters or numbers or both

I am searching for strings with only letters or numbers or both. How could I write a regex for that?
You can use following regex to check if the string contains letters and/or numbers
^[a-zA-Z0-9]+$
Explanation
^: Starts with
[]: Character class
a-zA-Z: Matches any alphabet
0-9: Matches any number
+: Matches previous characters one or more time
$: Ends with
RegEx101 Demo
"abc&#*(2743438" !~ /[^a-z0-9]/i # => false
"abc2743438" !~ /[^a-z0-9]/i # => true
This example let to avoid multiline anchors use (^ or $) (which may present a security risk) so it's better to use \A and \z, or to add the :multiline => true option in Rails.
Only letters and numbers:
/\A[a-zA-Z0-9]+\z/
Or if you want to leave - and _ chars also:
/\A[a-zA-Z0-9_\-]+\z/

How the Anchor \z and \G works in Ruby?

I am using Ruby1.9.3. I am newbie to this platform.
From the doc I just got familiared with two anchor which are \z and \G. Now I little bit played with \z to see how it works, as the definition(End or End of String) made me confused, I can't understand what it meant say - by End. So I tried the below small snippets. But still unable to catch.
CODE
irb(main):011:0> str = "Hit him on the head me 2\n" + "Hit him on the head wit>
=> "Hit him on the head me 2\nHit him on the head with a 24\n"
irb(main):012:0> str =~ /\d\z/
=> nil
irb(main):013:0> str = "Hit him on the head me 24 2\n" + "Hit him on the head >
=> "Hit him on the head me 24 2\nHit him on the head with a 24\n"
irb(main):014:0> str =~ /\d\z/
=> nil
irb(main):018:0> str = "Hit1 him on the head me 24 2\n" + "Hit him on the head>
=> "Hit1 him on the head me 24 2\nHit him on the head with a11 11 24\n"
irb(main):019:0> str =~ /\d\z/
=> nil
irb(main):020:0>
Every time I got nil as the output. So how the calculation is going on for \z ? what does End mean? - I think my concept took anything wrong with the End word in the doc. So anyone could help me out to understand the reason what is happening with the out why so happening?
And also i didn't find any example for the anchor \G . Any example please from you people to make visualize how \G used in real time programming?
EDIT
irb(main):029:0>
irb(main):030:0* ("{123}{45}{6789}").scan(/\G(?!^)\{\d+\}/)
=> []
irb(main):031:0> ('{123}{45}{6789}').scan(/\G(?!^)\{\d+\}/)
=> []
irb(main):032:0>
Thanks
\z matches the end of the input. You are trying to find a match where 4 occurs at the end of the input. Problem is, there is a newline at the end of the input, so you don't find a match. \Z matches either the end of the input or a newline at the end of the input.
So:
/\d\z/
matches the "4" in:
"24"
and:
/\d\Z/
matches the "4" in the above example and the "4" in:
"24\n"
Check out this question for example of using \G:
Examples of regex matcher \G (The end of the previous match) in Java would be nice
UPDATE: Real-World uses for \G
I came up with a more real world example. Say you have a list of words that are separated by arbitrary characters that cannot be well predicted (or there's too many possibilities to list). You'd like to match these words where each word is its own match up until a particular word, after which you don't want to match any more words. For example:
foo,bar.baz:buz'fuzz*hoo-har/haz|fil^bil!bak
You want to match each word until 'har'. You don't want to match 'har' or any of the words that follow. You can do this relatively easily using the following pattern:
/(?<=^|\G\W)\w+\b(?<!har)/
rubular
The first attempt will match the beginning of the input followed by zero non-word character followed by 3 word characters ('foo') followed by a word boundary. Finally, a negative lookbehind assures that the word which has just been matched is not 'har'.
On the second attempt, matching picks back up at the end of the last match. 1 non-word character is matched (',' - though it is not captured due to the lookbehind, which is a zero-width assertion), followed by 3 characters ('bar').
This continues until 'har' is matched, at which point the negative lookbehind is triggered and the match fails. Because all matches are supposed to be "attached" to the last successful match, no additional words will be matched.
The result is:
foo
bar
baz
buz
fuzz
hoo
If you want to reverse it and have all words after 'har' (but, again, not including 'har'), you can use an expression like this:
/(?!^)(?<=har\W|\G\W)\w+\b/
rubular
This will match either a word which is immediately preceeded by 'har' or the end of the last match (except we have to make sure not to match the beginning of the input). The list of matches is:
haz
fil
bil
bak
If you do want to match 'har' and all following words, you could use this:
/\bhar\b|(?!^)(?<=\G\W)\w+\b/
rubular
This produces the following matches:
har
haz
fil
bil
bak
Sounds like you want to know how Regex works? Or do you want to know how Regex works with ruby?
Check these out.
Regexp Class description
The Regex Coach - Great for testing regex matching
Regex cheat sheet
I understand \G to be a boundary match character. So it would tell the next match to start at the end of the last match. Perhaps since you haven't made a match yet you cant have a second.
Here is the best example I can find. Its not in ruby but the concept should be the same.
I take it back this might be more useful

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.
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.
/^([^_]*(_[^_])?)*_?$/
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'['__'])
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?
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_%*##+]+

Resources