【发布时间】:2015-07-05 15:39:53
【问题描述】:
我一直在使用以下代码来解决这个问题。我正在制作一个将 IUPAC 名称更改为结构的程序,所以我想分析用户输入的字符串。在 IUPAC 名称中也有括号。我想根据括号提取复合名称。我最后展示的方式。
我想修改方式,使输出变成这样并存储在数组中:
As ["(4'-氰基联苯-4-基)","5-[(4'-氰基联苯-4-基)氧基]", "({5-[(4'-氰基联苯-4-基)氧基]戊基}" ....等]
我写的分割代码是:
Reg_bracket=/([^(){}\[\]]*)([(){}\[\]])/
attr_reader :obrk, :cbrk
def count_level_br
@xbrk=0
@cbrk=0
if @temp1
@obrk+=1 if @temp1[1]=="(" || @temp1[1]=="[" ||@temp1[1]=="{"
@obrk-=1 if @temp1[1]==")" || @temp1[1]=="]" ||@temp1[1]=="}"
end
puts @obrk.to_s
end
def split_at_bracket(str=nil) #to split the brackets according to Regex
if str a=str
else a=self
end
a=~Reg_bracket
if $& @temp1=[$1,$2,$']
end
@temp1||=[a,"",""]
end
def find_block
@obrk=0 , r=""
@temp1||=["",""]
split_at_bracket
r<<@temp1[0]<<@temp1[1]
count_level_br
while @obrk!=0
split_at_bracket(@temp1[2])
r<<@temp1[0]<<@temp1[1]
count_level_br
puts r.to_s
if @obrk==0
puts "Level 0 has reached"
#puts "Close brackets are #{@cbrk}"
return r
end
end #end
end
end #class end'
我使用了正则表达式来匹配括号。然后当它找到任何括号时,它会给出匹配前、匹配后和匹配后第二个的结果,然后继续执行直到结束。
我现在得到的输出是这样的。
1
2
1-[(
3
1-[({
4
1-[({5-[
5
1-[({5-[(
4
1-[({5-[(4'-cyanobiphenyl-4-yl)
3
1-[({5-[(4'-cyanobiphenyl-4-yl)oxy]
2
1-[({5-[(4'-cyanobiphenyl-4-yl)oxy]pentyl}
1
1-[({5-[(4'-cyanobiphenyl-4-yl)oxy]pentyl}oxy)
0
1-[({5-[(4'-cyanobiphenyl-4-yl)oxy]pentyl}oxy)carbonyl]
Level 0 has reached
testing ends'
【问题讨论】:
-
你能发布你所拥有的输入和你想要的输出的样本
-
@IanKenney 我一开始就发布了我想要的输出结果。我给出的输入类似于 1-[({5-[(4'-cyanobiphenyl-4-yl)oxy]pentyl}oxy)carbonyl] ethane 化合物的 IUPAC 名称,输入字符串。
标签: ruby-on-rails ruby arrays string