If I understand with the term "capture", what you want is to remove the characters non-alphanumeric, use replace
, the negation regex must be so:
[^a-z0-9]
The sign of ^
inside [...]
denies any character, then replace will remove all that are not inside [^....]
Javascript should use with the modifier global
called /.../g
and with the /.../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);
Online example on ideone
Note:
It is important to realize that if you want to add more characters to are not removed, such as spaces, just add inside [^....]
, example that "captures" alphanumerics 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);
Capture in an array
If in fact you want to capture, then the correct is to use .match
in Javascript and preg_match
in PHP, regx would also change, to something a little more complex, considering that it is a string with different words and you want to capture all, so it has to be something like this:
(^|\s)([a-z0-9]*[^\s]*)(\s|$)
Example in Javascript:
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);
Is a string only or wants to capture multiple words in a string and separate them?
– Guilherme Nascimento