programing

JavaScript에서 문자열을 여러 구분자로 분할하려면 어떻게 해야 합니까?

copyandpastes 2022. 9. 13. 23:55
반응형

JavaScript에서 문자열을 여러 구분자로 분할하려면 어떻게 해야 합니까?

JavaScript에서 문자열을 여러 구분자로 분할하려면 어떻게 해야 합니까?

쉼표공백으로 나누려고 하는데 AFAIK JavaScript의split()이치노

파라미터로서 regexp를 전달합니다.

js> "Hello awesome, world!".split(/[\s,]+/)
Hello,awesome,world!

추가하도록 편집됨:

배열 길이에서 1을 뺀 값을 선택하면 마지막 요소를 얻을 수 있습니다.

>>> bits = "Hello awesome, world!".split(/[\s,]+/)
["Hello", "awesome", "world!"]
>>> bit = bits[bits.length - 1]
"world!"

...패턴이 일치하지 않는 경우:

>>> bits = "Hello awesome, world!".split(/foo/)
["Hello awesome, world!"]
>>> bits[bits.length - 1]
"Hello awesome, world!"

정규식을 JavaScript의 split() 메서드에 전달할 수 있습니다.예를 들어 다음과 같습니다.

"1,2 3".split(/,| /) 
["1", "2", "3"]

또는 여러 구분자를 함께 사용할 수 있도록 하는 경우 다음 절차를 수행합니다.

"1, 2, , 3".split(/(?:,| )+/) 
["1", "2", "3"]

((비캡처)를 (?:)괄호, 그렇지 않으면 결과에 다시 스플라이스됩니다.아니면 Aaron처럼 똑똑하게 캐릭터 클래스를 사용할 수도 있습니다.)

Safari 및 Firefox에서 테스트한 예.

간단하지만 효과적인 다른 방법은 분할 + 결합을 반복하는 것입니다.

"a=b,c:d".split('=').join(',').split(':').join(',').split(',')

기본적으로 조인에 이어 분할을 수행하는 것은 글로벌 치환과 같기 때문에 각 구분자를 콤마로 대체한 후 모두 교체한 후 콤마로 최종 분할을 수행합니다.

위의 식의 결과는 다음과 같습니다.

['a', 'b', 'c', 'd']

이를 확장하면 다음과 같은 함수에 배치할 수도 있습니다.

function splitMulti(str, tokens){
        var tempChar = tokens[0]; // We can use the first token as a temporary join character
        for(var i = 1; i < tokens.length; i++){
            str = str.split(tokens[i]).join(tempChar);
        }
        str = str.split(tempChar);
        return str;
}

사용방법:

splitMulti('a=b,c:d', ['=', ',', ':']) // ["a", "b", "c", "d"]

하면 랩핑도 해 볼 .String.prototype.split편의상(내 함수는 상당히 안전하다고 생각합니다.단, 고려해야 할 것은 조건(소수)의 추가 오버헤드와 배열을 통과했을 경우의 limit 인수의 구현이 부족하다는 점입니다).

시키세요.splitMulti이 접근방식을 사용하여 아래를 랩하는 경우 :)로 기능합니다., 빌트인을 가지는 사람이 잘못해 발생할 이 있기 에). SO에 하는 것이 에 할 필요가 있습니다.

    var splitOrig = String.prototype.split; // Maintain a reference to inbuilt fn
    String.prototype.split = function (){
        if(arguments[0].length > 0){
            if(Object.prototype.toString.call(arguments[0]) == "[object Array]" ) { // Check if our separator is an array
                return splitMulti(this, arguments[0]);  // Call splitMulti
            }
        }
        return splitOrig.apply(this, arguments); // Call original split maintaining context
    };

사용방법:

var a = "a=b,c:d";
    a.split(['=', ',', ':']); // ["a", "b", "c", "d"]

// Test to check that the built-in split still works (although our wrapper wouldn't work if it didn't as it depends on it :P)
        a.split('='); // ["a", "b,c:d"] 

맛있게 드세요!

단순하게 하자: (RegEx에 "[ ]+"를 추가하면 "1개 이상"을 의미합니다.)

즉, "+"와 "{1,}"이(가) 같다는 뜻입니다.

var words = text.split(/[ .:;?!~,`"&|()<>{}\[\]\r\n/\\]+/); // note ' and - are kept

까다로운 방법:

var s = "dasdnk asd, (naks) :d skldma";
var a = s.replace('(',' ').replace(')',' ').replace(',',' ').split(' ');
console.log(a);//["dasdnk", "asd", "naks", ":d", "skldma"]

아직 아무도 제안하지 않은 것에 놀랐습니다만, 제 해커는 같은 캐릭터로 나누기 전에 여러 개의 '대체' 콜을 추가하는 것이었습니다.

즉, a, b, c, d 및 e를 제거하려면:

let str = 'afgbfgcfgdfgefg'
let array = str.replace('a','d').replace('b','d').replace('c','d').replace('e','d').split('d')

이는 다음과 같이 스플리터 배열에 대해 쉽게 일반화할 수 있습니다.

function splitByMany( manyArgs, string ) {
  do {
    let arg = manyArgs.pop()
    string = string.replace(arg, manyArgs[0])
  } while (manyArgs.length > 2)
  return string.split(manyArgs[0])
}

그래서, 당신 경우엔, 전화하면

let array = splitByMany([" ", ","], 'My long string containing commas, and spaces, and more commas');

분할 기능을 보다 커스터마이즈 하고 싶은 분들을 위해 주어진 문자열을 분할할 수 있는 문자 목록으로 분할하는 재귀 알고리즘을 작성했습니다.위의 글을 보기 전에 이 글을 썼습니다.나는 그것이 몇몇 좌절하는 프로그래머들에게 도움이 되기를 바란다.

splitString = function(string, splitters) {
    var list = [string];
    for(var i=0, len=splitters.length; i<len; i++) {
        traverseList(list, splitters[i], 0);
    }
    return flatten(list);
}

traverseList = function(list, splitter, index) {
    if(list[index]) {
        if((list.constructor !== String) && (list[index].constructor === String))
            (list[index] != list[index].split(splitter)) ? list[index] = list[index].split(splitter) : null;
        (list[index].constructor === Array) ? traverseList(list[index], splitter, 0) : null;
        (list.constructor === Array) ? traverseList(list, splitter, index+1) : null;    
    }
}

flatten = function(arr) {
    return arr.reduce(function(acc, val) {
        return acc.concat(val.constructor === Array ? flatten(val) : val);
    },[]);
}

var stringToSplit = "people and_other/things";
var splitList = [" ", "_", "/"];
splitString(stringToSplit, splitList);

예: " " " " :["people", "and", "other", "things"]

★★★★★★flatten함수를 Rosetta Code에서 가져왔습니다.

구분자로 사용할 모든 문자를 단일 또는 집합적으로 정규 표현으로 묶어서 분할 함수에 전달할 수 있습니다.예를 들어 다음과 같이 쓸 수 있습니다.

console.log( "dasdnk asd, (naks) :d skldma".split(/[ \(,\)]+/) );

결과는 다음과 같습니다.

["dasdnk", "asd", "naks", ":d", "skldma"]

Regex 를 사용하면 도움이 될 수 있는 몇 가지 예를 다음에 나타냅니다.

  • \W 와 일치시키다[a-zA-Z0-9_] §:
("Hello World,I-am code").split(/\W+/); // would return [ 'Hello', 'World', 'I', 'am', 'code' ]
  • \s+ 의 공간을
  • \d
  • 는, 「」라고 하면 ., ★★★★★★★★★★★★★★★★★」- 하면 .str.split(/[,-]+/)...기타

나의 @Brian 답변 리팩터

var string = 'and this is some kind of information and another text and simple and some egample or red or text';
var separators = ['and', 'or'];

function splitMulti(str, separators){
            var tempChar = 't3mp'; //prevent short text separator in split down
            
            //split by regex e.g. \b(or|and)\b
            var re = new RegExp('\\b(' + separators.join('|') + ')\\b' , "g");
            str = str.replace(re, tempChar).split(tempChar);
            
            // trim & remove empty
            return str.map(el => el.trim()).filter(el => el.length > 0);
}

console.log(splitMulti(string, separators))

예를 들어 String 07:05:45로 분할 및 치환한 경우PM

var hour = time.replace("PM", "").split(":");

결과

[ '07', '05', '45' ]

나는 그러한 기능을 위한 고전적인 구현을 제공한다.이 코드는 거의 모든 버전의 JavaScript에서 작동하며 어느 정도 최적입니다.

  • 유지보수가 어려운 regex를 사용하지 않습니다.
  • JavaScript의 새로운 기능을 사용하지 않습니다.
  • 더 많은 컴퓨터 메모리가 필요한 여러 .split() .join() 호출을 사용하지 않습니다.

순수한 코드:

var text = "Create a function, that will return an array (of string), with the words inside the text";

println(getWords(text));

function getWords(text)
{
    let startWord = -1;
    let ar = [];

    for(let i = 0; i <= text.length; i++)
    {
        let c = i < text.length ? text[i] : " ";

        if (!isSeparator(c) && startWord < 0)
        {
            startWord = i;
        }

        if (isSeparator(c) && startWord >= 0)
        {
            let word = text.substring(startWord, i);
            ar.push(word);

            startWord = -1;
        }
    }

    return ar;
}

function isSeparator(c)
{
    var separators = [" ", "\t", "\n", "\r", ",", ";", ".", "!", "?", "(", ")"];
    return separators.includes(c);
}

놀이터에서 실행되는 코드를 볼 수 있습니다.https://codeguppy.com/code.html?IJI0E4OGnkyTZnoszAzf

URL을 .com/ 또는 .net/로 분할합니다.

url.split(/\.com\/|\.net\//)
a = "a=b,c:d"

array = ['=',',',':'];

for(i=0; i< array.length; i++){ a= a.split(array[i]).join(); }

그러면 특별한 샤렉터 없이 문자열이 반환됩니다.

ES6에서 동일한 기능을 실현하는 새로운 방법은 다음과 같습니다.

function SplitByString(source, splitBy) {
  var splitter = splitBy.split('');
  splitter.push([source]); //Push initial value

  return splitter.reduceRight(function(accumulator, curValue) {
    var k = [];
    accumulator.forEach(v => k = [...k, ...v.split(curValue)]);
    return k;
  });
}

var source = "abc,def#hijk*lmn,opq#rst*uvw,xyz";
var splitBy = ",*#";
console.log(SplitByString(source, splitBy));

이 기능에 주의해 주세요.

  • Regex 관련 없음
  • 을 에 합니다.source

상기 코드의 결과는 다음과 같습니다.

여기에 이미지 설명 입력

중 는 두 파일 입니다./ ★★★★★★★★★★★★★★★★★」\조금 까다로운 정규식이므로 참고용으로 여기에 게시합니다.

var splitFilePath = filePath.split(/[\/\\]/);

내 생각엔 네가 뭘 남기고 싶은지 명시하는 게 더 쉬울 것 같아, 뭘 없애고 싶은지 말이야.

마치 영어 단어만을 원하는 것처럼, 다음과 같은 것을 사용할 수 있습니다.

text.match(/[a-z'\-]+/gi);

예(실행 스니펫):

var R=[/[a-z'\-]+/gi,/[a-z'\-\s]+/gi];
var s=document.getElementById('s');
for(var i=0;i<R.length;i++)
 {
  var o=document.createElement('option');
  o.innerText=R[i]+'';
  o.value=i;
  s.appendChild(o);
 }
var t=document.getElementById('t');
var r=document.getElementById('r');

s.onchange=function()
 {
  r.innerHTML='';
  var x=s.value;
  if((x>=0)&&(x<R.length))
   x=t.value.match(R[x]);
  for(i=0;i<x.length;i++)
   {
    var li=document.createElement('li');
    li.innerText=x[i];
    r.appendChild(li);
   }
 }
<textarea id="t" style="width:70%;height:12em">even, test; spider-man

But saying o'er what I have said before:
My child is yet a stranger in the world;
She hath not seen the change of fourteen years,
Let two more summers wither in their pride,
Ere we may think her ripe to be a bride.

—Shakespeare, William. The Tragedy of Romeo and Juliet</textarea>

<p><select id="s">
 <option selected>Select a regular expression</option>
 <!-- option value="1">/[a-z'\-]+/gi</option>
 <option value="2">/[a-z'\-\s]+/gi</option -->
</select></p>
 <ol id="r" style="display:block;width:auto;border:1px inner;overflow:scroll;height:8em;max-height:10em;"></ol>
</div>

RegEx의 성능은 알 수 없지만, RegEx는 네이티브 HashSet을 활용하여 O(str.length, delimeter.length) 복잡도로 작동합니다.

var multiSplit = function(str,delimiter){
    if (!(delimiter instanceof Array))
        return str.split(delimiter);
    if (!delimiter || delimiter.length == 0)
        return [str];
    var hashSet = new Set(delimiter);
    if (hashSet.has(""))
        return str.split("");
    var lastIndex = 0;
    var result = [];
    for(var i = 0;i<str.length;i++){
        if (hashSet.has(str[i])){
            result.push(str.substring(lastIndex,i));
            lastIndex = i+1;
        }
    }
    result.push(str.substring(lastIndex));
    return result;
}

multiSplit('1,2,3.4.5.6 7 8 9',[',','.',' ']);
// Output: ["1", "2", "3", "4", "5", "6", "7", "8", "9"]

multiSplit('1,2,3.4.5.6 7 8 9',' ');
// Output: ["1,2,3.4.5.6", "7", "8", "9"]

C# 스트링의 대체품을 찾고 있던 중 우연히 이 질문을 받았습니다.인수 내의 문자를 사용하여 문자열을 분할하는 Split() 함수.

JavaScript 에서는 map an reduce를 사용하여 문자 분할과 중간 값 반복을 수행할 수 있습니다.

let splitters = [",", ":", ";"]; // or ",:;".split("");
let start= "a,b;c:d";
let values = splitters.reduce((old, c) => old.map(v => v.split(c)).flat(), [start]);
// values is ["a", "b", "c", "d"]

flat()은 중간 결과를 평탄화하기 위해 사용되며, 각 반복은 중첩된 배열 없이 문자열 목록에서 작동합니다.각 반복은 오래된 모든 값에 분할을 적용한 후 스플리터의 다음 값으로 분할되는 중간 결과 목록을 반환합니다.reduce()는 초기 문자열 값을 포함하는 배열로 초기화됩니다.

리덕션과 필터로 해결했습니다.가장 읽기 쉽거나 빠른 해결책은 아닐지도 모릅니다.실제로라면 아마 아론스를 사용하고 싶습니다만, 쓰는 것은 즐거웠습니다.

[' ','_','-','.',',',':','@'].reduce(
(segs, sep) => segs.reduce(
(out, seg) => out.concat(seg.split(sep)), []), 
['E-mail Address: user@domain.com, Phone Number: +1-800-555-0011']
).filter(x => x)

또는 함수로서:

function msplit(str, seps) {
  return seps.reduce((segs, sep) => segs.reduce(
    (out, seg) => out.concat(seg.split(sep)), []
  ), [str]).filter(x => x);
}

다음과 같이 출력됩니다.

['E','mail','Address','user','domain','com','0','Phone','Number','+1','800','555','0011']

마지막에 필터가 없으면 어레이 내에서 두 개의 다른 구분자가 나란히 있는 빈 문자열이 생성됩니다.

최적의 방법은 아니지만 여러 개의 다른 구분자/딜리미터를 사용하여 분할할 수 있습니다.

html

<button onclick="myFunction()">Split with Multiple and Different seperators/delimiters</button>
<p id="demo"></p>

자바스크립트

<script>
function myFunction() {

 var str = "How : are | you doing : today?";
 var res = str.split(' | ');

 var str2 = '';
 var i;
 for (i = 0; i < res.length; i++) { 
    str2 += res[i];
    
    if (i != res.length-1) {
      str2 += ",";
    }
 }
 var res2 = str2.split(' : ');

 //you can add countless options (with or without space)

 document.getElementById("demo").innerHTML = res2;
}
</script>

@stephen-sweriduk 솔루션(저에게는 더 흥미로웠습니다!)에서 시작하여 보다 범용적이고 재사용 가능한 솔루션을 만들기 위해 약간 수정했습니다.

/**
 * Adapted from: http://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript
*/
var StringUtils = {

  /**
   * Flatten a list of strings
   * http://rosettacode.org/wiki/Flatten_a_list
   */
  flatten : function(arr) {
    var self=this;
    return arr.reduce(function(acc, val) {
        return acc.concat(val.constructor === Array ? self.flatten(val) : val);
    },[]);
  },

  /**
   * Recursively Traverse a list and apply a function to each item
   * @param list array
   * @param expression Expression to use in func
   * @param func function of (item,expression) to apply expression to item
   *
   */
  traverseListFunc : function(list, expression, index, func) {
    var self=this;
    if(list[index]) {
        if((list.constructor !== String) && (list[index].constructor === String))
            (list[index] != func(list[index], expression)) ? list[index] = func(list[index], expression) : null;
        (list[index].constructor === Array) ? self.traverseListFunc(list[index], expression, 0, func) : null;
        (list.constructor === Array) ? self.traverseListFunc(list, expression, index+1, func) : null;
    }
  },

  /**
   * Recursively map function to string
   * @param string
   * @param expression Expression to apply to func
   * @param function of (item, expressions[i])
   */
  mapFuncToString : function(string, expressions, func) {
    var self=this;
    var list = [string];
    for(var i=0, len=expressions.length; i<len; i++) {
        self.traverseListFunc(list, expressions[i], 0, func);
    }
    return self.flatten(list);
  },

  /**
   * Split a string
   * @param splitters Array of characters to apply the split
   */
  splitString : function(string, splitters) {
    return this.mapFuncToString(string, splitters, function(item, expression) {
      return item.split(expression);
    })
  },

}

그리고 나서.

var stringToSplit = "people and_other/things";
var splitList = [" ", "_", "/"];
var splittedString=StringUtils.splitString(stringToSplit, splitList);
console.log(splitList, stringToSplit, splittedString);

원본으로 돌려주는 것:

[ ' ', '_', '/' ] 'people and_other/things' [ 'people', 'and', 'other', 'things' ]

간단한 방법은 각 딜리미터를 사용하여 문자열의 각 문자를 처리하고 분할 배열을 작성하는 것입니다.

splix = function ()
{
  u = [].slice.call(arguments); v = u.slice(1); u = u[0]; w = [u]; x = 0;

  for (i = 0; i < u.length; ++i)
  {
    for (j = 0; j < v.length; ++j)
    {
      if (u.slice(i, i + v[j].length) == v[j])
      {
        y = w[x].split(v[j]); w[x] = y[0]; w[++x] = y[1];
      };
    };
  };
  
  return w;
};

console.logg = function ()
{
  document.body.innerHTML += "<br>" + [].slice.call(arguments).join();
}

splix = function() {
  u = [].slice.call(arguments);
  v = u.slice(1);
  u = u[0];
  w = [u];
  x = 0;
  console.logg("Processing: <code>" + JSON.stringify(w) + "</code>");

  for (i = 0; i < u.length; ++i) {
    for (j = 0; j < v.length; ++j) {
      console.logg("Processing: <code>[\x22" + u.slice(i, i + v[j].length) + "\x22, \x22" + v[j] + "\x22]</code>");
      if (u.slice(i, i + v[j].length) == v[j]) {
        y = w[x].split(v[j]);
        w[x] = y[0];
        w[++x] = y[1];
        console.logg("Currently processed: " + JSON.stringify(w) + "\n");
      };
    };
  };

  console.logg("Return: <code>" + JSON.stringify(w) + "</code>");
};

setTimeout(function() {
  console.clear();
  splix("1.23--4", ".", "--");
}, 250);
@import url("http://fonts.googleapis.com/css?family=Roboto");

body {font: 20px Roboto;}

사용방법:splix(string, delimiters...)

예:splix("1.23--4", ".", "--")

반품:["1", "23", "4"]

Github에 있는 내 간단한 라이브러리 확인하세요.

repo를 방문하거나 대화하고 싶지 않은 경우 작업 코드는 다음과 같습니다.

/**
 * 
 * @param {type} input The string input to be split
 * @param {type} includeTokensInOutput If true, the tokens are retained in the splitted output.
 * @param {type} tokens The tokens to be employed in splitting the original string.
 * @returns {Scanner}
 */
function Scanner(input, includeTokensInOutput, tokens) {
    this.input = input;
    this.includeTokensInOutput = includeTokensInOutput;
    this.tokens = tokens;
}

Scanner.prototype.scan = function () {
    var inp = this.input;

    var parse = [];
    this.tokens.sort(function (a, b) {
        return b.length - a.length; //ASC, For Descending order use: b - a
    });
    for (var i = 0; i < inp.length; i++) {


        for (var j = 0; j < this.tokens.length; j++) {

            var token = this.tokens[j];
            var len = token.length;
            if (len > 0 && i + len <= inp.length) {
                var portion = inp.substring(i, i + len);
                if (portion === token) {
                    if (i !== 0) {//avoid empty spaces
                        parse[parse.length] = inp.substring(0, i);
                    }
                    if (this.includeTokensInOutput) {
                        parse[parse.length] = token;
                    }
                    inp = inp.substring(i + len);
                    i = -1;
                    break;
                }

            }

        }

    }
    if (inp.length > 0) {
          parse[parse.length] = inp;
    }

    return parse;


};

사용법은 매우 간단합니다.

    var tokens = new Scanner("ABC+DE-GHIJK+LMNOP", false , new Array('+','-')).scan();

console.log(tokens); 

제공 내용:

['ABC', 'DE', 'GHIJK', 'LMNOP']

분할 토큰을 포함하려면(+ and -)출력으로,false로.true그리고 voila! 여전히 작동한다.

사용 방법은 다음과 같습니다.

var tokens = new Scanner("ABC+DE-GHIJK+LMNOP", true , new Array('+','-')).scan();

그리고.

console.log(tokens);

다음과 같은 것을 얻을 수 있습니다.

['ABC', '+', 'DE', '-', 'GHIJK', '+', 'LMNOP']

즐기세요!

regexp를 사용합니다.

str =  'Write a program that extracts from a given text all palindromes, e.g. "ABBA", "lamal", "exe".';

var strNew = str.match(/\w+/g);

// Output: ["Write", "a", "program", "that", "extracts", "from", "a", "given", "text", "all", "palindromes", "e", "g", "ABBA", "lamal", "exe"]

언급URL : https://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript

반응형