简体   繁体   English

Javascript正则表达式选择每个非字母数字字符和空格?

[英]Javascript Regex to select every non-alphanumeric character AND whitespace?

I'm new to JS, tried using - 我是JS新手,尝试使用-

/[0-9a-z]+$/gi
/[^0-9a-z]+$/gi

neither worked. 都不起作用。 Can anyone tell me where I am going wrong? 谁能告诉我我要去哪里错了?

Replace 更换

var sentence_split = arr.split(/[0-9a-z]+$/gi);

with

var sentence_split = arr.split(/[^0-9a-z]+/gi);

... if you prefer to go this way. ...如果您喜欢这种方式。

Explanation: the original regex was anchored (with $ ) to the end of the string, and splitted by words - and not symbols separating them. 说明:原始正则表达式(用$ )锚定在字符串的末尾,并按单词分隔-而不是用符号分隔它们。

Still, there's more than one way to do the things you do: I'd probably go just with: 尽管如此,还有多种方法可以完成您要做的事情:我可能会选择:

var words = sentence.match(/(\w+)/g);

... capturing sequences of word-consisting symbols instead of splitting the phrase by something that separates them. ...捕获包含单词的符号序列,而不是用将它们分开的方式将短语分开。 Here's a Fiddle to play with. 这是一个小提琴

UPDATE: And one last thing. 更新:还有最后一件事。 I felt a bit... uneasy about wasting sort just to get max essentially. 我感到有点...对于仅仅为了max地获得max浪费sort感到不安。 I don't know if you share these thoughts, still here's how I would update the searching code: 我不知道您是否同意这些想法,仍然是我将如何更新搜索代码的方法:

var longest;
words.forEach(function(e) {
  if (! longest || longest.length < e.length) {
    longest = e;
  }
});

It's forEach , because I'm a bit lazy and imagine having a luxury of NOT working with IE8-; 这是forEach ,因为我有点懒惰,并且可以想象不使用IE8-是一种奢侈。 still, it's quite easy to rewrite this into a regular for... array-walking routine. 尽管如此,将其重写为常规for...数组遍历例程还是很容易的。

Updated fiddle . 更新小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 正则表达式“密码必须至少包含一个非字母数字字符” - Regex for “password must contain at least one non-alphanumeric character” RegEx(在JavaScript中查找/替换) - 匹配非字母数字字符但忽略 - 和+ - RegEx (in JavaScript find/replace) - match non-alphanumeric characters but ignore - and + Javascript Regex替换任何非字母数字字符,包括方括号 - Javascript Regex to replace any non-alphanumeric characters, including brackets 如何防止javascript中的非字母数字输入? - How to prevent non-alphanumeric input in javascript? Javascript字符串替换 - 非字母数字字符的RegEx,如反斜杠,大于等等 - Javascript String Replace - RegEx for Non-Alphanumeric Characters Like Backslash, Greater Than, etc 从字符串中删除特定的非字母数字字符 - Removing spesific non-alphanumeric character from a string 过滤掉 JavaScript 中的所有非字母数字字符 - Filtering out all non-alphanumeric characters in JavaScript Javascript正则表达式:匹配非空格字符的任何非单词字符 - Javascript Regex: Match any non-word character that is not a whitespace character 如何仅匹配第一次出现的字母数字字符,前面是非字母数字字符? - How to match only the first occurrence of an alphanumeric character, preceded by a non-alphanumeric character? javascript在非字母数字上拆分,并在开始时保留分隔符 - javascript split on non-alphanumeric an keep delemiters at start
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM