Java에서 구분 기호를 제거하지 않고 일부 구분 기호로 문자열을 분할하는 방법은 무엇입니까?
이 질문에 이미 답변이 있습니다.
분할에 문제가 String있습니다.
나는 분리자를 String잃지 않고 분리 하고 싶습니다 .
somestring.split(String separator)Java에서 메소드를 사용하면을 분할 String하지만 String. 이런 일이 일어나길 원하지 않습니다.
다음과 같은 결과를 원합니다.
String string1="Ram-sita-laxman";
String seperator="-";
string1.split(seperator);
산출:
[Ram, sita, laxman]
하지만 대신 아래와 같은 결과를 원합니다.
[Ram, -sita, -laxman]
이와 같은 출력을 얻는 방법이 있습니까?
string1.split("(?=-)");
이것은 split실제로 정규식을 취하기 때문에 작동 합니다 . 실제로보고있는 것은 "폭이 0 인 긍정 예측"입니다.
더 설명하고 싶지만 딸이 다과회를하고 싶어요. :)
편집 : 뒤로!
이를 설명하기 위해 먼저 다른 split작업을 보여 드리겠습니다 .
"Ram-sita-laxman".split("");
이것은 길이가 0 인 모든 문자열에서 문자열을 분할합니다. 모든 문자 사이에 길이가 0 인 문자열이 있습니다. 따라서 결과는 다음과 같습니다.
["", "R", "a", "m", "-", "s", "i", "t", "a", "-", "l", "a", "x", "m", "a", "n"]
이제 정규식 ( "")을 수정 하여 길이가 0 인 문자열 에 대시가 오는 경우 에만 일치 시킵니다.
"Ram-sita-laxman".split("(?=-)");
["Ram", "-sita", "-laxman"]
이 예에서 ?=의미는 "예측"입니다. 보다 구체적으로 " 긍정적 인 예측"을 의미 합니다. 왜 "긍정적"입니까? 대시가 뒤 따르지 않는 길이가 0 인 모든 문자열에서 분할되는 음의 미리보기 ( ?!)를 가질 수도 있기 때문입니다 .
"Ram-sita-laxman".split("(?!-)");
["", "R", "a", "m-", "s", "i", "t", "a-", "l", "a", "x", "m", "a", "n"]
대시가 앞에 오는 길이가 0 인 모든 문자열에서 분할되는 긍정적 인 lookbehind ( ?<=)를 가질 수도 있습니다 .
"Ram-sita-laxman".split("(?<=-)");
["Ram-", "sita-", "laxman"]
마지막으로 대시 가 없는 길이가 0 인 모든 문자열에서 분할되는 부정적인 lookbehind ( ?<!)를 가질 수도 있습니다 .
"Ram-sita-laxman".split("(?<!-)");
["", "R", "a", "m", "-s", "i", "t", "a", "-l", "a", "x", "m", "a", "n"]
이 네 가지 식을 통칭하여 둘러보기 식이 라고 합니다.
보너스 : 합치기
최근에 만난 두 개의 둘러보기 표현식 을 결합한 예제를 보여 드리고 싶었습니다 . CapitalCase 식별자를 토큰으로 분할하려고한다고 가정합니다.
"MyAwesomeClass" => ["My", "Awesome", "Class"]
다음 정규식을 사용하여이를 수행 할 수 있습니다.
"MyAwesomeClass".split("(?<=[a-z])(?=[A-Z])");
This splits on every zero-length string that is preceded by a lower case letter ((?<=[a-z])) and followed by an upper case letter ((?=[A-Z])).
This technique also works with camelCase identifiers.
It's a bit dodgy, but you could introduce a dummy separator using a replace function. I don't know the Java methods, but in C# it could be something like:
string1.Replace("-", "#-").Split("#");
Of course, you'd need to pick a dummy separator that's guaranteed not to be anywhere else in the string.
A way to do this is to split your string, then add your separator at the beginning of each extracted string except the first one.
seperator="-";
String[] splitstrings = string1.split(seperator);
for(int i=1; i<splitstring.length;i++)
{
splitstring[i] = seperator + splitstring[i];
}
that is the code fitting to LadaRaider's answer.
Adam hit the nail on the head! I used his answer to figure out how to insert filename text from the file dialog browser into a rich text box. The problem I ran into was when I was adding a new line at the "\" in the file string. The string.split command was splitting at the \ and deleting it. After using a mixture of Adam's code I was able to create a new line after each \ in the file name.
Here is the code I used:
OpenFileDialog fd = new OpenFileDialog();
fd.Multiselect = true;
fd.ShowDialog();
foreach (string filename in fd.FileNames)
{
string currentfiles = uxFiles.Text;
string value = "\r\n" + filename;
//This line allows the Regex command to split after each \ in the filename.
string[] lines = Regex.Split(value, @"(?<=\\)");
foreach (string line in lines)
{
uxFiles.Text = uxFiles.Text + line + "\r\n";
}
}
Enjoy!
Walrusking
'Program Club' 카테고리의 다른 글
| "던지기"는 무엇입니까? (0) | 2020.11.14 |
|---|---|
| 프로그래밍 방식으로 GIF 애니메이션 중지 (0) | 2020.11.14 |
| 타이머를 어떻게 중지합니까? (0) | 2020.11.12 |
| Android ADT 오류, dx.jar이 SDK 폴더에서로드되지 않았습니다. (0) | 2020.11.12 |
| 정적 방법과 비 정적 방법의 차이점은 무엇입니까? (0) | 2020.11.12 |