当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - How to remove everything in between parenthesis and trailing space from string?

问题描述:

I need to remove everything between all of the parenthesis in a string as well as the trailing space before the comma, how can I do this in ruby on rails? I've found out how to do it when the string is always the same but since the value inside the parenthesis isn't always the same all the methods that I've found fail.

The value inside the parenthesis can be 1 to 3 digits so a possible solution has to account for different value lengths.

Sample string:

2(2) , 12(3) , 20(2) , 21(5)

Outcome that I want:

2, 12, 20, 21

I tried using this regex:

/(... )

Which captures the first 3 matches, but not the last one since it doesn't have a trailing space.

Using only (...) causes a match from 2(2) , 12(3) , 20(2) , 21(5 for some reason.

How can I create a proper regex for this or possibly a better solution?

网友答案:

Try this:

x = "2(2) , 12(3) , 20(2) , 21(5)"
x.gsub(/\(.*?\)/, '')

网友答案:
s = "2(2) , 12(3) , 20(2) , 21(5)"
s.gsub(/\(.*?\) ?/, '')
 => "2, 12, 20, 21" 

This should be working.

网友答案:

Thisone also worked for me (s stands for input-string):

ar = s.split(',').each.map { |el| el.strip.match(/(\d*)[^\(]/) }
result = ar.each.map {|el| el[0]}

It's a bit huge and not very pretty, but does the job :)

分享给朋友:
您可能感兴趣的文章:
随机阅读: