Pergunta

I'm trying to create an array of elements drawn from a regular expression that include punctuation symbols, but I get only get a single value.

Thi is the String Example

'00000002 BLABLA'<MADRID CENTRO>,'00000006 FAFAFAFA'<BARCELONA ORIENTE>,'00000919 HUAWEI'<LA CANDELA>,

I want an array like those values, including separators:

'00000002 BLABLA'<MADRID CENTRO>,

My wrong regular expression:

 regex = /^'[0-9]{8}\s[a-zA-Z\'{1}]*[\<{1}a-zA-Z\>{1}]*/;
Foi útil?

Solução

How about

var re = /'\d{8} [a-z]+'<[^>]+>,/ig

str.match(re);
/*  [
       "'00000002 BLABLA'<MADRID CENTRO>,",
       "'00000006 FAFAFAFA'<BARCELONA ORIENTE>,",
       "'00000919 HUAWEI'<LA CANDELA>,"
    ] */

Outras dicas

because you are using ^

use this :

''[0-9]{8}\s[a-zA-Z\'{1}]*[\<{1}a-zA-Z\>{1}][^,]+,/g

demo here : http://regex101.com/r/nZ7nZ9

check this out :

var str = "'00000002 BLABLA'<MADRID CENTRO>,'00000006 FAFAFAFA'<BARCELONA ORIENTE>,'00000919 HUAWEI'<LA CANDELA>,";
var res = str.match(/('[0-9]{8}\s[a-zA-Z\'{1}]*[\<{1}a-zA-Z\>{1}][^,]+,)/g);
console.log(res);

o/p:

["'00000002 BLABLA'<MADRID CENTRO>,", "'00000006 FAFAFAFA'<BARCELONA ORIENTE>,", "'00000919 HUAWEI'<LA CANDELA>,"]

This regex works for me:

'[0-9]{8}\s[a-zA-Z\'{1}]*[\<{1}a-zA-Z\s\>,{1}]*

You should use this tool to test regex : http://www.gethifi.com/tools/regex

EDIT: like @aelor said, you're using ^ which will only match with a start of line. I also add \s to catch whitespaces in the last part of your expression (like

Your errors:

  • You've used the start-of-line anchor (^). Of course you only ever get one match: the one at the start of the line.
  • You seem to think that character classes ([]) are some form of grouping. They are not.
  • Angle brackets have no meaning in JS regular exressions, you don't have to escape them.
  • You say you want to match the separators but you did not include them in your expression
  • You did not use the global modifier (g)
  • You could use the case-insensitive modifier (i)

Better

var regex = /'[0-9]{8}\s[a-z]*'<[a-z ]*>,/ig;

In any case: It could be that you're over-specific. What about:

var regex = /'[^']*'<[^>]*>,/g;

Overly specific regular expressions are hard to debug and maintain while providing no real benefit. (Careful with not-specific-enough expressions, though. Find the right balance.)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top