programing

첫 번째 공백 발생 시 분할 문자열

subpage 2023. 7. 23. 14:16
반응형

첫 번째 공백 발생 시 분할 문자열

첫 번째 공백을 기준으로 문자열을 분할하는 최적화된 정규식을 얻지 못했습니다.

var str="72 tocirah sneab";

다음을 수행해야 합니다.

[
    "72",
    "tocirah sneab",
]

공백 문자(탭이나 다른 공백 문자는 제외)만 사용하고 첫 번째 공백 이전의 모든 항목과 첫 번째 공백 이후의 모든 항목만 사용하는 경우 다음과 같은 정규식 없이도 사용할 수 있습니다.

str.substring(0, str.indexOf(' ')); // "72"
str.substring(str.indexOf(' ') + 1); // "tocirah sneab"

공백이 전혀 없는 경우 첫 번째 줄은 빈 문자열을 반환하고 두 번째 줄은 전체 문자열을 반환합니다.해당 상황에서 원하는 동작인지 확인합니다(또는 해당 상황이 발생하지 않음).

Javascript는 Lookbackback을 지원하지 않기 때문에split불가능합니다.match편집:편집:

str.match(/^(\S+)\s(.*)/).slice(1)

또 다른 속임수:

str.replace(/\s+/, '\x01').split('\x01')

어때요?

[str.replace(/\s.*/, ''), str.replace(/\S+\s/, '')]

그리고 왜 안됩니까?

reverse = function (s) { return s.split('').reverse().join('') }
reverse(str).split(/\s(?=\S+$)/).reverse().map(reverse)

아니면 아마도

re = /^\S+\s|.*/g;
[].concat.call(re.exec(str), re.exec(str))

2019년 업데이트: ES2018 기준, 룩백이 지원됩니다.

str = "72 tocirah sneab"
s = str.split(/(?<=^\S+)\s/)
console.log(s)

ES6에서는 또한

let [first, ...second] = str.split(" ")
second = second.join(" ")

게임이 늦어진 것은 알지만 이를 위한 매우 간단한 방법이 있는 것 같습니다.

const str = "72 tocirah sneab";
const arr = str.split(/ (.*)/);
console.log(arr);

이것은 떠날 것입니다.arr[0]와 함께"72"그리고.arr[1]와 함께"tocirah sneab"는 비어 그냥.arr[2]는 파일 이름입니다.

참조용:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#Capturing_parentheses

var arr = [];             //new storage
str = str.split(' ');     //split by spaces
arr.push(str.shift());    //add the number
arr.push(str.join(' '));  //and the rest of the string

//arr is now:
["72","tocirah sneab"];

하지만 저는 여전히 더 빠른 방법이 있다고 생각합니다.

Georg의 솔루션은 좋지만 문자열에 공백이 없으면 중단됩니다.문자열에 공백이 없을 가능성이 있는 경우 .split을 사용하여 다음과 같은 그룹을 캡처하는 것이 더 안전합니다.

str_1 = str.split(/\s(.+)/)[0];  //everything before the first space
str_2 = str.split(/\s(.+)/)[1];  //everything after the first space

.replace를 사용하여 첫 번째 항목만 바꿀 수 있습니다.

​str = str.replace(' ','<br />');

/g는 빼고요.

데모

공간이 부족한 부분도 처리하면서 한 줄로 다 할 수 있는데 왜 다른 모든 답변들이 그렇게 복잡한지 모르겠습니다.

예를 들어, 이름의 첫 번째와 "나머지" 구성 요소를 가져옵니다.

const [first, rest] = 'John Von Doe'.split(/\s+(.*)/);
console.log({ first, rest });

// As array
const components = 'Surma'.split(/\s+(.*)/);
console.log(components);

줄을 배열로 나누고 필요한 부분을 접착제로 붙이기만 하면 됩니다.이 접근 방식은 매우 유연하며 여러 상황에서 작동하며 추론하기 쉽습니다.또한 함수 호출이 하나만 필요합니다.

arr = str.split(' ');             // ["72", "tocirah", "sneab"]
strA = arr[0];                    // "72"
strB = arr[1] + ' ' + arr[2];     // "tocirah sneab"

또는 문자열에서 직접 필요한 항목을 선택하려면 다음과 같은 작업을 수행할 수 있습니다.

strA = str.split(' ')[0];                    // "72";
strB = str.slice(strA.length + 1);           // "tocirah sneab"

이런 식으로.

strA = str.split(' ')[0];                    // "72";
strB = str.split(' ').splice(1).join(' ');   // "tocirah sneab"

하지만 저는 첫 번째 예를 제안합니다.

작업 데모: jsbin

사용한 적이 있습니다..split(" ")[0]공간 앞에 있는 모든 문자를 가져옵니다.

productName.split(" ")[0]

또 다른 간단한 방법:

str = 'text1 text2 text3';
strFirstWord = str.split(' ')[0];
strOtherWords = str.replace(strFirstWord + ' ', '');

결과:

strFirstWord = 'text1';
strOtherWords = 'text2 text3';

클래스 목록이나 클래스 이름 또는 ID의 일부에서 클래스를 가져와야 할 때마다 항상 split()를 사용하여 배열 인덱스와 함께 클래스를 가져오거나, 대부분의 경우 pop()을 사용하여 마지막 요소나 shift()를 먼저 가져옵니다.

이 예에서는 div의 클래스 "gallery_148 ui-sortable"을 가져오고 gallery id 148을 반환합니다.

var galleryClass = $(this).parent().prop("class"); // = gallery_148 ui-sortable
var galleryID = galleryClass.split(" ").shift(); // = gallery_148
galleryID = galleryID.split("_").pop(); // = 148
//or
galleryID = galleryID.substring(8); // = 148 also, but less versatile 

저는 그것이 더 적은 줄로 압축될 수 있다고 확신하지만, 읽기 쉽도록 확장된 채로 두었습니다.

저는 약간 다른 결과가 필요했습니다.

저는 첫 단어를 원했고, 그 이후에 무엇이 오든지 간에, 비록 그것이 비어 있더라도.

str.substr(0, text.indexOf(' ') == -1 ? text.length : text.indexOf(' '));
str.substr(text.indexOf(' ') == -1 ? text.length : text.indexOf(' ') + 1);

그래서 만약 입력이oneword당신은oneword그리고.''.

입력이 다음과 같은 경우one word and some more당신은one그리고.word and some more.

위의 대부분의 답변은 공백이 아닌 공백으로 검색합니다.@그들의 대답은 좋습니다.저는 약간 다른 버전을 가지고 있습니다.

s.trim().split(/\s(.*)/).splice(0,2)

내 것은 regexp가 훨씬 간단해서 어떤 것이 가장 효율적인지 어떻게 구분해야 할지 잘 모르겠지만, 여분의 장소가 있습니다.

(@filename's 참조)s.split(/(?<=^\S+)\s/))

이 질문은 공백이 없거나 모든 공백, 선행 또는 후행 공백 또는 빈 문자열을 처리하는 방법을 지정하지 않으며, 이러한 경우 결과는 미묘하게 다릅니다.

저는 다음 단어를 사용해야 하는 파서를 위해 이 글을 씁니다. 그래서 저는 제 정의를 선호합니다. @georg's가 다른 사용 사례에 더 적합할 수도 있습니다.

input.        mine              @georg
'aaa bbb'     ['aaa','bbb']     ['aaa','bbb']
'aaa bbb ccc' ['aaa','bbb ccc'] ['aaa','bbb ccc']
'aaa '        [ 'aaa' ]         [ 'aaa', '' ]
' '           [ '' ]            [ ' ' ]
''            ['']              ['']
' aaa'        ['aaa']           [' aaa']
"72 tocirah sneab".split(/ (.*)/,2)

지정된 결과를 생성합니다.

[ '72', 'tocirah sneab' ]

공간 앞에 첫 번째 하위 문자열을 얻는 것이 목적이라면 아래가 가장 좋으며 공간이 없으면 빈 문자열이 반환되지 않습니다.

var str = "string1 string2";
str = str.trim();
if(str.indexOf(' ')!==-1)
 str = str.substring(0, str.indexOf(' ')); 

다음 기능은 항상 문장을 두 요소로 나눕니다.첫 번째 요소는 첫 번째 단어만 포함하고 두 번째 요소는 다른 모든 단어를 포함합니다(또는 빈 문자열이 됩니다).

var arr1 = split_on_first_word("72 tocirah sneab");       // Result: ["72", "tocirah sneab"]
var arr2 = split_on_first_word("  72  tocirah sneab  ");  // Result: ["72", "tocirah sneab"]
var arr3 = split_on_first_word("72");                     // Result: ["72", ""]
var arr4 = split_on_first_word("");                       // Result: ["", ""]

function split_on_first_word(str)
{
    str = str.trim();  // Clean string by removing beginning and ending spaces.

    var arr = [];
    var pos = str.indexOf(' ');  // Find position of first space

    if ( pos === -1 ) {
        // No space found
        arr.push(str);                // First word (or empty)
        arr.push('');                 // Empty (no next words)
    } else {
        // Split on first space
        arr.push(str.substr(0,pos));         // First word
        arr.push(str.substr(pos+1).trim());  // Next words
    }

    return arr;
}

언급URL : https://stackoverflow.com/questions/10272773/split-string-on-the-first-white-space-occurrence

반응형