Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用正则表达式对字符串进行切片和切割_Javascript_Regex - Fatal编程技术网

Javascript 使用正则表达式对字符串进行切片和切割

Javascript 使用正则表达式对字符串进行切片和切割,javascript,regex,Javascript,Regex,我对Regex模式感兴趣,它将跳转到第一个非空白字符,返回该索引,然后从那里返回下一个空白字符,然后返回该索引 基本上,我要做的是从字符串中提取一个单词。但我还想保留索引,因为我需要在不使用我们刚刚提取的单词的情况下重建该字符串 诸如此类: var start = txt.search(/\S/); //this gets the index of the first non whitespace character var end = txt.search(/\s/); //this gets

我对Regex模式感兴趣,它将跳转到第一个非空白字符,返回该索引,然后从那里返回下一个空白字符,然后返回该索引

基本上,我要做的是从字符串中提取一个单词。但我还想保留索引,因为我需要在不使用我们刚刚提取的单词的情况下重建该字符串

诸如此类:

var start = txt.search(/\S/); //this gets the index of the first non whitespace character
var end = txt.search(/\s/); //this gets the index of the first whitespace character
var word = txt.slice(start,end); //get the word
txt = txt.slice(end); //update txt to hold the rest of the string
该实现的问题是,如果第一个空白字符出现在第一个非空白字符之前,我们会得到不想要的结果

如果.search有一个开始索引,那将非常有帮助,但除此之外,我被难倒了

试着用更好的词来表达:


我需要第一个非空白字符的索引,然后是第一个非空白字符后面的第一个空白字符的索引。这将允许我从字符串中获取一个单词

如果你真的想去掉句子中的单词,你有两个选择: 1.修剪句子,这很容易,但因为你想保留第一句话。还有下一个选择。 2.把句子分成一个数组

var txt = " this is a sentece ";
var words = txt.split(/\W/);
while(words.indexOf("") !== -1) {
    words.splice(words.indexOf(""), 1);
}
现在单词
[“this”,“is”,“a”,“sencee”]

这个怎么样

var string = "      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
    matches = [],
    re = /\S+/g,
    match;

while (match = re.exec(string)){
    matches.push(match);
}

/* matches = [
    [0: "Lorem"
     index: 6
     input: "      Lorem Ipsum is simply dummy te..."],
    [0: "Ipsum"
     index: 12
     input: "      Lorem Ipsum is simply dummy te..."],

     ...

]; */

用什么条件把一个词拔出来?