대괄호가 포함된 Ruby 문자열을 배열로 어떻게 변환하나요?

StackOverflow https://stackoverflow.com/questions/38409

  •  09-06-2019
  •  | 
  •  

문제

다음 문자열을 배열/중첩 배열로 변환하고 싶습니다.

str = "[[this, is],[a, nested],[array]]"

newarray = # this is what I need help with!

newarray.inspect  # => [['this','is'],['a','nested'],['array']]
도움이 되었습니까?

해결책

YAML을 사용하면 원하는 것을 얻을 수 있습니다.

하지만 문자열에 약간의 문제가 있습니다.YAML은 쉼표 뒤에 공백이 있을 것으로 예상합니다.그래서 우리는 이것이 필요합니다

str = "[[this, is], [a, nested], [array]]"

암호:

require 'yaml'
str = "[[this, is],[a, nested],[array]]"
### transform your string in a valid YAML-String
str.gsub!(/(\,)(\S)/, "\\1 \\2")
YAML::load(str)
# => [["this", "is"], ["a", "nested"], ["array"]]

다른 팁

웃으려면:

 ary = eval("[[this, is],[a, nested],[array]]".gsub(/(\w+?)/, "'\\1'") )
 => [["this", "is"], ["a", "nested"], ["array"]]

부인 성명:당신은 확실히 이렇게해서는 안됩니다 eval 끔찍한 생각이지만 빠르고 중첩된 배열이 유효하지 않은 경우 예외를 발생시키는 유용한 부작용이 있습니다.

거의 JSON으로 처리할 수도 있습니다.귀하의 예와 같이 문자열이 실제로 문자로만 구성된 경우 다음과 같이 작동합니다.

JSON.parse(yourarray.gsub(/([a-z]+)/,'"\1"'))

임의의 문자( [ ] , 제외)를 가질 수 있는 경우 조금 더 필요합니다.

JSON.parse("[[this, is],[a, nested],[array]]".gsub(/, /,",").gsub(/([^\[\]\,]+)/,'"\1"'))

기본적인 구문 분석 작업처럼 보입니다.일반적으로 취하려는 접근 방식은 다음 일반 알고리즘을 사용하여 재귀 함수를 만드는 것입니다.

base case (input doesn't begin with '[') return the input
recursive case:
    split the input on ',' (you will need to find commas only at this level)
    for each sub string call this method again with the sub string
    return array containing the results from this recursive method

여기서 유일하게 약간 까다로운 부분은 입력을 단일 ','로 분할하는 것입니다.문자열을 스캔하고 지금까지 본 닫힌 브래킷인 열린 브래킷의 수를 유지하는 별도의 함수를 작성할 수 있습니다.그런 다음 개수가 0과 같을 때만 쉼표로 분할합니다.

문자열과 정수 오프셋을 취하고 배열을 "읽는" 재귀 함수를 만듭니다.즉, 배열이나 문자열(읽은)과 배열 뒤를 가리키는 정수 오프셋을 반환하도록 합니다.예를 들어:

s = "[[this, is],[a, nested],[array]]"

yourFunc(s, 1) # returns ['this', 'is'] and 11.
yourFunc(s, 2) # returns 'this' and 6.

그런 다음 오프셋 0을 제공하고 종료 오프셋이 문자열 길이인지 확인하는 다른 함수를 사용하여 이를 호출할 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top