Programing

정규 표현식을 사용하여 Ruby의 문자열에서 부분 문자열 추출

lottogame 2020. 7. 20. 21:13
반응형

정규 표현식을 사용하여 Ruby의 문자열에서 부분 문자열 추출


Ruby의 문자열 내에서 하위 문자열을 추출하려면 어떻게해야합니까?

예:

String1 = "<name> <substring>"

나는 추출 할 substring에서 String1(마지막에 출현 내 즉 모든 <>).


String1.scan(/<([^>]*)>/).last.first

scan캡처 그룹을 포함하는 정규식과 함께 사용될 때 scan은 각 일치에 대한 캡처를 포함하는 배열을 만듭니다)는 각각 <item>String1대해 <>요소 사이에 텍스트를 포함하는 배열을 만듭니다. last마지막 배열 first을 제공 하고 그 안에 문자열을 제공합니다.


"<name> <substring>"[/.*<([^>]*)/,1]
=> "substring"

scan결과가 하나만 필요한 경우을 사용할 필요가 없습니다 . 우리가있을 때
사용할 필요가 없습니다 .matchString[regexp,#]

참조 : http://ruby-doc.org/core/String.html#method-i-5B-5D

노트 : str[regexp, capture] → new_str or nil


정규 표현식을 아주 쉽게 사용할 수 있습니다…

단어 주위에 공백을 허용 (그러나 유지하지는 않음) :

str.match(/< ?([^>]+) ?>\Z/)[1]

또는 공백이 허용되지 않은 경우 :

str.match(/<([^>]+)>\Z/)[1]

이 방법을 사용하는 약간 더 유연한 접근법이 match있습니다. 이를 통해 둘 이상의 문자열을 추출 할 수 있습니다.

s = "<ants> <pants>"
matchdata = s.match(/<([^>]*)> <([^>]*)>/)

# Use 'captures' to get an array of the captures
matchdata.captures   # ["ants","pants"]

# Or use raw indices
matchdata[0]   # whole regex match: "<ants> <pants>"
matchdata[1]   # first capture: "ants"
matchdata[2]   # second capture: "pants"

보다 간단한 스캔은 다음과 같습니다.

String1.scan(/<(\S+)>/).last

참고 URL : https://stackoverflow.com/questions/4115115/extract-a-substring-from-a-string-in-ruby-using-a-regular-expression

반응형