.NET의 regex를 사용하여 문자열에서 모든 {} 토큰을 어떻게 추출합니까?

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

  •  20-08-2019
  •  | 
  •  

문제

주어진 끈에서 곱슬 괄호로 표시된 토큰을 추출해야합니다.

나는 expresso를 사용하여 구문 분석 할 무언가를 만들어 냈습니다 ...

-------------------------------------------------------------
"{Token1}asdasasd{Token2}asd asdacscadase dfb db {Token3}"
-------------------------------------------------------------

"Token1", "Token2", "Token3"을 생산합니다.

사용해 보았습니다 ..

-------------------------------------------------------------
({.+})
-------------------------------------------------------------

... 그러나 그것은 전체 표현과 일치하는 것처럼 보였다.

이견있는 사람?

도움이 되었습니까?

해결책

노력하다

\{(.*?)\}
The \{ will escape the "{" (which has meaning in a RegEx).
The \} likewise escapes the closing } backet.
The .*? will take minimal data, instead of just .* 
which is "greedy" and takes everything it can.
If you have assurance that your tokens will (or need to) 
be of a specific format, you can replace .* with an appropriate 
character class. For example, in the likely case you 
want only words, you can use (\w*) in place of the (.*?) 
This has the advantage that closing } characters are not 
part of the class being matched in the inner expression, 
so you don't need the ? modifier). 

다른 팁

노력하다:

\{([^}]*)\}

이것은 뾰족한 브레이스 내부의 검색을 고정하여 닫는 버팀대에서 멈출 것입니다.

다른 해결책 :

(?<=\{)([^\}]+)(?=\})

이것은 곡예선과 외관을 사용하여 괄호가 전혀 소비되지 않습니다.

곱슬 괄호는 정규 표현에서 특별한 의미를 지니고 있으므로 탈출해야합니다. 사용 \{ 그리고 \} 그들과 일치합니다.

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