2012-12-22 2 views
2

기본 분할 문자열 조작은 알고 있지만 VB.NET 초보자는 매개 변수 (토큰)를 사용하여 문자열을 분할하는 편리한 방법이 있는지 알고 싶습니다.
문자열의 크기와 내용은 다를 수 있지만 항상 "[parameter] -> value"스키마가 동일합니다. 이처럼
:문자열을 매개 변수와 값으로 분할

[name] John [year] 1990 [gender]M[state] Washington[married] No[employed] No 

방법이 구문 분석은, syntacticly 나쁜 파라미터 유효> 값 쌍을 얻을 수있는 문자열을 작성?

편집 : 코드, 정규식 또는 유사한 예를 들어주세요.

+0

당신은 정규 표현식을 사용하여 시도해야합니다. – MarcinJuraszek

+0

안녕하세요 마크, 비슷한 상황에 대한 예를 들어 링크를 제공 할 수 있습니까? –

답변

3

당신은 정규 표현식으로이 작업을 수행 할 수 있습니다

Dim RegexObj As New Regex(_ 
    "\[   # Match an opening bracket"       & chr(10) & _ 
    "(?<name> # Match and capture into group ""name"":"   & chr(10) & _ 
    " [^[\]]* # any number of characters except brackets"   & chr(10) & _ 
    ")   # End of capturing group"       & chr(10) & _ 
    "\]   # Match a closing bracket"       & chr(10) & _ 
    "\s*  # Match optional whitespace"      & chr(10) & _ 
    "(?<value> # Match and capture into group ""value"":"   & chr(10) & _ 
    " [^[\]]*? # any number of characters except brackets"   & chr(10) & _ 
    ")   # End of capturing group"       & chr(10) & _ 
    "(?=  # Assert that we end this match either when"  & chr(10) & _ 
    " \s*\[  # optional whitespace and an opening bracket"  & chr(10) & _ 
    "|   # or"            & chr(10) & _ 
    " \s*$  # whitespace and the end of the string"    & chr(10) & _ 
    ")   # are present after the current position", _ 
    RegexOptions.IgnorePatternWhitespace) 
Dim MatchResults As Match = RegexObj.Match(SubjectString) 
While MatchResults.Success 
    parameter = MatchResults.Groups("name").Value 
    value = MatchResults.Groups("value").Value 
    ' do something with the parameter/value pairs 
    MatchResults = MatchResults.NextMatch() 
End While 
+0

코드가 작동하지만 표현식을 작성하지 못하므로 결과가 표시되지 않습니다. 나는 이것을 쓰다 ... im RegexObj 새로운 Regex (("\ [\]"), RegexOptions.IgnorePatternWhitespace)는 매개 변수 이름을 얻지 만 그런 식으로는 가지 않는다. –

+1

어, 나는별로 따라하지 않습니다. 내 대답에 제공된 정규식에는 이미 매개 변수와 값을 일치시키는 모든 것이 들어 있습니다. –

+0

죄송합니다 Tim. 1 번줄과 15 번 줄 끝 부분에 밑줄을 넣는 것을 잊어 버리면 IDE에 오류가 표시됩니다. 놀라운 예! 예상대로 작동합니다. 고마워요! –

관련 문제