str = 'this#is#an#example#using#myword#also'
array = str.split('#')
array[-2] == 'myword' ? array[-2..-1].join('#') : array[-1]
With regex:
'this#is#an#example'[/(myword\#)*\w+$/]
# => "example"
'this#is#an#example#using#myword#also'[/(myword\#)*\w+$/]
# => "myword#also"
그러나
str = 'this#is#an#example'
str[/(?:#)((myword#)?[^#]+)$/, 1]
#=> "example"
str = 'this#is#an#example#using#myword#also'
str[/(?:#)((myword#)?[^#]+)$/, 1]
#=> "myword#also"
, 나는 정규 표현식을 사용하여 생각하지 않습니다이 경우 "더 나은"입니다 . 나는 Santosh (삭제 된) 답변과 같은 것을 사용할 것이다 : 라인을 #
으로 나눠서 if 절을 사용하자.
def foo(str)
*, a, b = str.split('#')
if a == 'myword'
"#{a}##{b}"
else
b
end
end
답장을 보내 주셔서 감사합니다. 불행히도 귀하의 발췌 문장은 "두 번째로 분할하고 확인하는 것보다 더 좋은 방법이 있습니까?"라는 질문에 대한 대답이 아닙니다. – macsig