openlang

저장한 문자열로 만들면 Ruby 정규식이 동작하지 않습니다

다음 변수에 정규식을 보관하고 있습니다 - pattern_text = "/\A([^@\s]+)@((?:c-d+\.)+(in|com))\z/".

"mailbox@c-d.in".match?(/\A([^@\s]+)@((?:c-d+\.)+(in|com))\z/) => returns true
Regexp.new(pattern_text) => returns /\/A([^@ ]+)@((?:c-d+.)+(in|com))z\//
"mailbox@c-d.in".match?(Regexp.new(pattern_text)) => returns false

이 정규식을 데이터베이스에 저장하면 \가 자동으로 사라집니다. 제가 받는 정규식 검증기는 문자열로 들어옵니다. 왜 이 형태는 동작하지 않을까요?

영어에서 번역원문 보기

이어지는 대화 2

서로의 근거를 따라
  1. 고유 링크

    큰따옴표 문자열 대신 작은따옴표 문자열을 쓰세요 (이 설명을 보세요 (https://en.wikibooks.org/wiki/Ruby_Programming/Strings#Single_quotes))

    > puts "/\A([^@\s]+)@((?:c-d+\.)+(in|com))\z/"
    /A([^@ ]+)@((?:c-d+.)+(in|com))z/
    
    > puts '/\A([^@\s]+)@((?:c-d+\.)+(in|com))\z/'
    /\A([^@\s]+)@((?:c-d+\.)+(in|com))\z/

    그다음 양 끝의 '/'를 없애세요:

    > pattern_text = '\A([^@\s]+)@((?:c-d+\.)+(in|com))\z'
    => "\\A([^@\\s]+)@((?:c-d+\\.)+(in|com))\\z"
    
    > compiled = Regexp.new(pattern_text)
    => /\A([^@\s]+)@((?:c-d+\.)+(in|com))\z/
    
    > "mailbox@c-d.in".match?(Regexp.new(compiled))
    => true
    영어에서 번역원문 보기
  2. 고유 링크

    정규식 패턴을 나중에 쓰려고 데이터베이스에 넣을 때는 보통 패턴 / 플래그를 문자열로 표현해서 저장합니다.

    따라서 정규식 정보를 모두 한 열에 넣으려면 Regexp#to_s (https://ruby-doc.org/core-2.5.1/Regexp.html#method-i-to_s)를 쓸 수 있습니다:

    stored_expression = /.../.to_s

    패턴 (source (https://ruby-doc.org/core-2.5.1/Regexp.html#method-i-source))과 플래그 (options (https://ruby-doc.org/core-2.5.1/Regexp.html#method-i-options))를 별도의 문자열로 저장하려면:

    stored_pattern = /\A([^@\s]+)@((?:c-d+\.)+(in|com))\z/.source
    stored_flags   = /\A([^@\s]+)@((?:c-d+\.)+(in|com))\z/.options

    데이터베이스에서 값을 읽어 온 뒤 Regexp.new 생성자 (https://ruby-doc.org/core-2.5.1/Regexp.html#method-c-new)로 정규식 객체를 복원하세요:

    expression = Regexp.new(stored_expression)
    # alternatively
    expression = Regexp.new(stored_pattern, stored_flags)

    Ruby의 Regexp 문서 (https://ruby-doc.org/core-2.5.1/Regexp.html)를 참고하세요.

    영어에서 번역원문 보기

같은 질문의 다른 갈래

  1. String.Format을 호출할 때 퍼센트 문자는 어떻게 이스케이프하나요?

    strings.xml 파일에 SQL 쿼리를 저장해 두고, 코드에서 String.Format으로 최종 문자열을 만들려고 해요. SELECT 쿼리에는 이런 like 절이 들어 있어요: 서식을 적용하려고 'pattern'을 %1$…

    답글 3최근 활동 java
  2. F#에서 문자열 서식 지정하기

    처음으로 F# 라이브러리를 만들고 있어요 string.Format를 사용하면 그런 함수가 없다는 오류가 나와요. 제가 잘못한 걸까요, 아니면 원래 없는 기능인가요?

    답글 2최근 활동 fsharp
  3. tcl 문자열에서 한 부분 추출하기

    tcl로 Reports/Report#2.rpt를 나눠서 Report#2.rpt만 남기려고 해요 ; 다음 방법을 시도했지만 실행해도 아무 출력이 없었어요 :

    답글 2최근 활동 tcl