3

I am trying to match any group of characters until a line break like this: \n. I want to be able to access all groups matched then.

The text I am using to look for my regular expression is like this :

foo foo!\n *bar bar*\n *foo :* foo bar\n*foo :* 32 foo bar\n*Bar :* 37 foo foo\n*Time :* 11:00:00-14:00:00\n*Date :* 2016-12-23\n*Foo :* \n*bar* : 06XXXXXXXX

For now, I tried multiple solutions and the best working is this regex:

/([^\\n])\w+/

but it it still not perfect. It doesn't take the special chars nor spaces into account.

3
  • 1
    The s.match(/.+/g) should be enough. Or even s.split("\n"). Can there be CR symbols in the string? Dec 23, 2016 at 18:44
  • Your [^\\n] is going to match anything except a real backslash and a real n, which is almost certainly not what you want. You might try [^\n], but unfortunately \n` does not work within a character set.
    – user663031
    Dec 23, 2016 at 19:29
  • What is the expected output? Dec 23, 2016 at 20:19

1 Answer 1

2

What you need to is match at least one (+) char that is not new-line (\n):

s = 'foo foo!\n *bar bar*\n *foo :* foo bar\n*foo :* 32 foo bar\n*Bar :* 37 foo foo\n*Time :* 11:00:00-14:00:00\n*Date :* 2016-12-23\n*Foo :* \n*bar* : 06XXXXXXXX'

console.log(s.match(/([^\n]+)/g))

3
  • The funny thing is that your regexp would still work if you replaced the [^\n] with a dot, and by the way you don't need the parens either.
    – user663031
    Dec 23, 2016 at 19:34
  • @torazaburo, there are many ways write regex things :) a dot indeed is one of them :) btw, a voteup will be much appreciated!
    – Dekel
    Dec 23, 2016 at 19:53
  • You should double check it. The \n is indeed meaningful in character class. Run my example :)
    – Dekel
    Dec 23, 2016 at 21:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.