/^(.*)\./
only captures everything up to the dot. The "com" is not captured and thus not replaced in the substitution.
Why is my regular expression skipping the dot instead of matching the string before it?
Frage
I was trying to work out a regular expression in IRB and got some unexpected output. The goal was to match everything up until the last dot in a FQDN.
So, for example, if I was trying to match the string "flowtechconsulting.com"
,
I started with the following:
s1.sub(/^(.*)\\./, "\\1") #=> "flowtechconsultingcom"
However, the sub
function simply returned everything but the dot, instead of the first matching group.
If I add two matching groups it works:
s1.sub(/^(.*)\\.(.*)$/, "\\1") #=> "flowtechconsulting"
I'm just not sure why the first doesn't work. It seems like it should.
Lösung
Andere Tipps
Forget about sub
, and do something like:
"foo.bar.baz.com"[/(.*)(?:\.)/, 1]
# => "foo.bar.baz"
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow