Ich würde einen regulären Ausdruck in Kombination mit den Methoden String#count, String#[] und String#tr verwenden.
R =/
\A # match start of string
.+?,\s+ # match >= 1 characters lazily (`?`) follow by a comma and >= 1 spaces
\K # forget everything matched so far
.+ # match >= 1 characters greedily
(?=,\s+\S+\z) # match a comma, >= 1 spaces, >= 1 characters other than
# sapces and end of string in a positive lookahead
/x # free-spacing regex definition mode
def doit(str)
str.count(',') <= 1 ? nil : str[R].tr(',', ' ')
end
doit "11, 12, 13, 14"
#=> "12 13"
doit "1, 4"
#=> nil
doit "1"
#=> nil
doit ""
#=> nil
Die Schritte sind wie folgt.
str = "11, 12, 13, 14"
str.count(',') <= 1
#=> false
s = str[R]
#=> "12, 13"
s.tr(',', ' ')
#=> "12 13"
str = "1, 4"
str.count(',') <= 1
#=> true
nil
Dieser reguläre Ausdruck würde konventionell
/\A.+?,\s+\K.+(?=,\s+\S+\z)/
Sie alternativ eine Aufnahme geschrieben werden Gruppe in der Regex anstelle der beiden lookarounds verwenden:
R =/
\A # match start of string
.+?,\s+ # match >= 1 characters lazily (`?`), a comma and >= 1 spaces
(.+) # match one or more characters (greedily) in capture group 1
,\s+\S+ # match a comma, >= 1 spaces, >= 1 characters other than spaces
\z # match end of string
/x # free-spacing regex definition mode
und dann
def doit(str)
str.count(',') <= 1 ? nil : str[R,1].tr(',', ' ')
end
Die Auswahl ist allgemein verfügbar. Ich bevorzuge Lookarounds oder \K
, aber es ist eine persönliche Vorliebe.
Vielen Dank das ist toll, vor allem für die Erklärung der Probleme mit meinem Code! Wirklich hilft mir, es auch besser zu verstehen. – loopylou