gpt4 book ai didi

javascript - 在 Javascript 中使用正则表达式标记字符串

转载 作者:搜寻专家 更新时间:2023-11-01 04:55:20 24 4
gpt4 key购买 nike

假设我有一个包含换行符和制表符的长字符串:

var x = "This is a long string.\n\t This is another one on next line.";

那么我们如何使用正则表达式将这个字符串拆分成标记呢?

我不想使用 .split(' ') 因为我想学习 Javascript 的正则表达式。

一个更复杂的字符串可能是这样的:

var y = "This @is a #long $string. Alright, lets split this.";

现在我只想从这个字符串中提取有效的,没有特殊字符和标点符号,即我想要这些:

var xwords = ["This", "is", "a", "long", "string", "This", "is", "another", "one", "on", "next", "line"];

var ywords = ["This", "is", "a", "long", "string", "Alright", "lets", "split", "this"];

最佳答案

这是您所问内容的 jsfiddle 示例:http://jsfiddle.net/ayezutov/BjXw5/1/

基本上,代码很简单:

var y = "This @is a #long $string. Alright, lets split this.";
var regex = /[^\s]+/g; // This is "multiple not space characters, which should be searched not once in string"

var match = y.match(regex);
for (var i = 0; i<match.length; i++)
{
document.write(match[i]);
document.write('<br>');
}

更新:基本上您可以扩展分隔符列表:http://jsfiddle.net/ayezutov/BjXw5/2/

var regex = /[^\s\.,!?]+/g;

更新 2:始终只有字母: http://jsfiddle.net/ayezutov/BjXw5/3/

var regex = /\w+/g;

关于javascript - 在 Javascript 中使用正则表达式标记字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8441915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com