문제

Regex에 관해서는 완전한 아마추어라고 말하면서 이것을 서두르고 며칠 전에 시작했습니다. 파일을 형식화하는 문제를 해결하려고 노력하고 있으며 특정 유형의 데이터로 히치를 쳤다. 입력 파일은 다음과 같이 구성됩니다.

Two words,Word,Word,Word,"Number, number"

내가해야 할 일은 이렇게 형식화하는 것입니다 ...

"Two words","Word",Word","Word","Number, number"

나는 Regex 패턴을 가졌다

s/,/","/g

작동하는 경우를 제외하고는 이미 인용 된 번호 인 번호 섹션의 쉼표를 대체하여 필드가 파일을 분리하고 중단하게합니다. 본질적으로, 나는 쉼표를 ",[Quote Comma Quote]로 대체하기 위해 내 패턴을 수정해야하지만, 그 쉼표가 공간을 따라 가지 않을 때만 가능합니다. 다른 필드에는 쉼표 이후의 공간이 없으며 구분 된 번호 목록 만 있습니다.

나는 글을 쓸 수 있었다

s/,[A-Za-z0-9]/","/g

적절한 문자열과 일치하는 동안 쉼표와 다음 문자를 대체합니다. 나는 뒷받침에 대해 들었고 그것이 내가 사용해야 할 것이라고 생각합니까? 내 이해는 그거였습니다

s/(,)[A-Za-z0-9]\b

작동해야하지만 그렇지 않습니다.

누구든지 아이디어가 있습니까?

도움이 되었습니까?

해결책

s/,([^ ])/","$1/ will match a "," followed by a "not-a-space", capturing the not-a-space, then replacing the whole thing with the captured part.

Depending on which regex engine you're using, you might be writing \1 or other things instead of $1.

If you're using Perl or otherwise have access to a regex engine with negative lookahead, s/,(?! )/","/ (a "," not followed by a space) works.

Your input looks like CSV, though, and if it actually is, you'd be better off parsing it with a real CSV parser rather than with regexes. There's lot of other odd corner cases to worry about.

다른 팁

My experience has been that this is not a great use of regexes. As already said, CSV files are better handled by real CSV parsers. You didn't tag a language, so it's hard to tell, but in perl, I use Text::CSV_XS or DBD::CSV (allowing me SQL to access a CSV file as if it were a table, which, of course, uses Text::CSV_XS under the covers). Far simpler than rolling my own, and far more robust than using regexes.

This question is similar to: Replace patterns that are inside delimiters using a regular expression call.

This could work:

s/"([^"]*)"|([^",]+)/"$1$2"/g

Looks like you're using Sed.

While your pattern seems to be a little inconsistent, I'm assuming you'd like every item separated by commas to have quotations around it. Otherwise, you're looking at areas of computational complexity regular expressions are not meant to handle.

Through sed, your command would be:

  sed 's/[ \"]*,[ \"]*/\", \"/g'

Note that you'll still have to put doublequotes at the beginning and end of the string.

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