简体   繁体   中英

How to split an array into words while keeping words inside square brackets together in JavaScript or AS3?

I'm trying to write a function in AS3 and/or JavaScript that will let me take a string that has words enclosed in square brackets and keep them together, while splitting the rest. So for example, it would take a sentence like this:

This is [an example] of a sentence that has [groups of words] enclosed in [square brackets.]

And turn it into an array like this:

[This,is,an example,of,a,sentence,that,has,groups of words,enclosed,in,square brackets.]

What would be the most efficient way to accomplish this? I'm guessingit would use some kind of regex, probably with lookahead and/or lookbehind. Any ideas?

This regular expression should do it : /[^[][([^]]+)]|(\\w+)/g;

It search for all word within square bracket and made a group or all word outside.

Example (javascript):

var testStr="This is [an example] of a sentence that has [groups of words] enclosed in [square brackets.]";

var reSentence = /[^\[]\[([^\]]+)\]|(\w+)/g;
var matchObject;
var result=[];
while(matchObject=reSentence .exec(testStr))
      result.push(matchObject[1] || matchObject[2]);
console.log(result);

javascript live example : http://jsfiddle.net/UNxB9/

Example (as3):

var testStr:String="This is [an example] of a sentence that has [groups of words] enclosed in [square brackets.]";

var reSentence:RegExp = /[^\[]\[([^\]]+)\]|(\w+)/g;
var matchObject:Object;
var result:Array=[];
while(matchObject=reSentence .exec(testStr))
      result.push(matchObject[1] || matchObject[2]);
trace(result);

as3 live example : http://wonderfl.net/c/2MiG

Just thinking out loud here... My first try would be a regex to match, and then store and replace brackets (and content) with some sort of unique symbol. Then split the string by spaces and then replace the symbols in the array with the with the bracket content in the same order it was removed.

Not sure on efficiency at this point but you gotta start somewhere. Hope this gets things going.

This will do it:

function splitWithBracket(str) {
    var out = str.split(" "), i = 0, begin, end;

    function findNext(chr) {
        while (i < out.length) {
            if (out[i].indexOf(chr) != -1) {
                out[i] = out[i].replace(chr, "");
                return(i);
            }
            i++;
        }
        return(-1);
    }

    do {
        end = -1;
        begin = findNext("[");
        if (begin != -1) {
            end = findNext("]");
            if (end != -1) {
                var tmp = out.splice(begin, end - begin + 1);
                out.splice(begin, 0, tmp.join(" "));
                i = begin + 1;
            }
        }
    } while (end != -1);
    return(out);
}

Work demo: http://jsfiddle.net/jfriend00/jLNXa/

Or a version using regular expression replacement/matching:

function splitWithBracket(str) {
    str = str.replace(/\[([^\]]*)\]/g, function(m, p1) {
            return(p1.replace(/ /g, "!!xx!!"));
    });
    var out = str.split(" ");
    for (var i = 0; i < out.length; i++) {
        out[i] = out[i].replace(/!!xx!!/g, " ")
    }
    return(out);
}

Working demo: http://jsfiddle.net/jfriend00/Hbjzk/

try this one:

var str = 'This is [an example] of a sentence that has [groups of words] enclosed in [square brackets.]';
var finder = /\[?([^\[\]]+)\]?/g;
var result;
while( ( result = finder.exec( str ) ) !== null ){
    console.log( result );
}

good luck!

This will do the work, http://jsfiddle.net/mwfHn/2/ :

    <script>
    myStr = "This is [an example] of a sentence that has [groups of words] enclosed in [square brackets.]";
    myStr = myStr.replace(/\[[a-zA-Z. ]+\]/g, function(match){ return match.replace(/\s+/g,"#").replace(/\[|\]/g,""); }).split(" ").join(",").replace(/#/g," ");
    alert(myStr);
   </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM