If I understood the term "capture", what you want is to remove the non-alphanumeric characters , use replace
, the deny regex should look like this:
[^a-z0-9]
The sign of ^
within [...]
deny any character, then replace will remove all those that are not within [^....]
In JavaScript you should use with the modifier global
called /.../g
and with /.../i
if you need case-insensitive, example:
var str = "m,.o,e.d...a";
var resposta = str.replace(/[^a-z0-9]/gi, "");
console.log(resposta);
In PHP it would be like this, with preg_replace
:
$str = "m,.o,e.d...a";
$resposta = preg_replace('#[^a-z0-9]#', '', $str);
var_dump($resposta);
Example online at ideone
Note:
It's important to note that if you want to add more characters to not be removed, such as spaces, just add within [^....]
, example that captures alphanumeric characters and spaces:
var str = "m,.o,e.d...a ,.n,.a,. ,.,.c,.a,.r,.t,.e,.i,.r,.a";
var resposta = str.replace(/[^a-z0-9\s]/gi, "");
console.log(resposta);
Capturing into an array
If you really want to capture, then the correct one is to use .match
in JavaScript and preg_match
in PHP, regx would also change to something a bit more complex considering that it is a string with different words and you want capture all, then it has to be something like this:
(^|\s)([a-z0-9]*[^\s]*)(\s|$)
JavaScript example:
var str = "m,.o,e.d...a ,.n,.a,. ,.,.c,.a,.r,.t,.e,.i,.r,.a";
var respostas = str.match(/(^|\s)([^\s]+?)(\s|$)/gi, "");
var allowAN = /[^a-z0-9]/gi;
for (var i = 0, j = respostas.length; i < j; i++) {
respostas[i] = respostas[i].trim().replace(allowAN, "");
}
console.log(respostas);