Regex

I have this example:

ReplaceStrRegex(
  Trim(
    "     qweqwe    \n asdasdasd  asdadsad    \n\n\n\n    asdasdasd"
  ),
  "\\s{1,}",
  " "
)

and when I run it, it returns:

qweqwe asdasdasd asdadsad asdasdasd

So for some reason, instead of just clearing out spaces, it also cleared out newlines.

However, if I do this:

ReplaceStrRegex(
  Trim(
    "     qweqwe    \n asdasdasd  asdadsad    \n\n\n\n    asdasdasd"
  ),
  "\\n{1,}",
  " "
)

The returned output is:

qweqwe      asdasdasd  asdadsad         asdasdasd

Which is correct because it only cleaned the newlines

And if I do this:

ReplaceStrRegex(
  Trim(
    "     qweqwe    \n asdasdasd  asdadsad    \n\n\n\n    asdasdasd"
  ),
  "\\n{2,}",
  " \n"
)

The output is:

qweqwe    
 asdasdasd  asdadsad         asdasdasd

Which is also correct because it only cleared out the multiple new lines.

So I’m not sure what’s different with the \s{1,} that it clears even the new lines.

Answering my own question:

ReplaceStrRegex(
  Trim(
    "     qweqwe    \n asdasdasd  asdadsad    \n\n\n\n    asdasdasd"
  ),
  " {1,}",
  " "
)

instead of using \s, I used a literal <space>. Not sure why \s is behaving that way.

The output will be:

qweqwe 
 asdasdasd asdadsad 



 asdasdasd

\s is equivalent to [ \t\r\n\v\f], so the new lines were included. New lines are white-space characters.

I found this Stack Overflow answer with a trick to get non-new-line whitespace: regex - Match whitespace but not newlines - Stack Overflow

/[^\S\r\n]/

ReplaceStrRegex(
  Trim(
    "     qweqwe    \n asdasdasd  asdadsad    \n\n\n\n    asdasdasd"
  ),
  "[^\\S\\r\\n]{1,}",
  " "
)
1 Like

AHA that’s a weird java behaviour, in javascript \s is just white space and not newline :sweat_smile:

You mean that’s a weird JS behaviour.

According to MDN \s should match newline. Where are you using JS that it’s not matching \n?

2 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.