Ruby replace string with captured regex pattern

后端 未结 6 1953
庸人自扰
庸人自扰 2021-01-31 13:13

I am having trouble translating this into Ruby.

Here is a piece of JavaScript that does exactly what I want to do:

function get_code(str){
    return str         


        
6条回答
  •  無奈伤痛
    2021-01-31 13:49

    If you need to use a regex to filter some results, and THEN use only the capture group, you can do the following:

    str = "Leesburg, Virginia  20176"
    state_regex = Regexp.new(/,\s*([A-Za-z]{2,})\s*\d{5,}/)
    # looks for the comma, possible whitespace, captures alpha,
    # looks for possible whitespace, looks for zip
    
    > str[state_regex]
    => ", Virginia  20176"
    
    > str[state_regex, 1] # use the capture group
    => "Virginia"
    

提交回复
热议问题