简体   繁体   English

使用 RegEx 提取单词

[英]Extract words with RegEx

I am new with RegEx, but it would be very useful to use it for my project.我是 RegEx 的新手,但将它用于我的项目会非常有用。 What I want to do in Javascript is this :我想在 Javascript 中做的是:

I have this kind of string "/this/is/an/example" and I would like to extract each word of that string, that is to say :我有这种字符串“/this/is/an/example”,我想提取该字符串的每个单词,也就是说:

"/this/is/an/example" -> this, is, an, example. "/this/is/an/example" -> this, is, an, example。 And then use each word.然后使用每个单词。

Up to now, I did :到目前为止,我做了:

var str = "/this/is/a/test"; 
var patt1 = /\/*/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;

and it returns me : /,,,,,/,,,/,,/,,,,,它返回我:/,,,,,/,,,/,,/,,,,,

I know that I will have to use .slice function next if I can identify the position of each "/" by using search for instance but using search it only returns me the index of the first "/" that is to say in this case 0.我知道如果我可以通过使用搜索来识别每个“/”的位置,我知道接下来我将不得不使用 .slice 函数,但使用搜索它只会返回第一个“/”的索引,也就是说在这种情况下0.

I cannot find out.我查不出来。

Any Idea ?任何的想法 ?

Thanks in advance !提前致谢 !

Use split()使用split()

The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split. split() 方法通过将字符串分成子字符串来将字符串对象拆分为字符串数组,使用指定的分隔符字符串来确定每次拆分的位置。

 var str = "/this/is/a/test"; var array = str.split('/'); console.log(array);

In case you want to do with regex.如果您想使用正则表达式。

 var str = "/this/is/a/test"; var patt1 = /(\\w+)/g; var result = str.match(patt1) console.log(result);

Well I guess it depends on your definition of 'word', there is a 'word character' match which might be what you want:好吧,我想这取决于您对“单词”的定义,有一个“单词字符”匹配可能正是您想要的:

var patt1 = /(\w+)/g;

Here is a working example of the regex这是正则表达式的工作示例

Full JS example:完整的 JS 示例:

 var str = "/this/is/a/test"; var patt1 = /(\\w+)/g; var match = str.match(patt1); var output = match.join(", "); console.log(output);

You can use this regex: /\\b[^\\d\\W]+\\b/g , to have a specific word just access the index in the array.您可以使用此正则表达式: /\\b[^\\d\\W]+\\b/g ,让特定单词只需访问数组中的索引即可。 eg result[0] == this例如result[0] == this

 var str = "/this/is/a/test"; var patt1 = /\\b[^\\d\\W]+\\b/g; var result = str.match(patt1); document.getElementById("demo").innerHTML = result;
 <span id="demo"></span>

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

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