RegEx: Starts With WORDA But Doesn't Contain WORDB

I need to validate some msg.payload data in a Switch Node. To be valid, the data must start with WORDA but not contain WORDB. The data spans multiple lines (has newlines) and WORDB, if present and invalidating the data, could be anywhere on any line.

Must it be regex? A simple function would do the job using calls to the string functions startsWith & contains

if ( msg.payload.startsWith("WORDA")  && !msg.payload.contains("WORDB")) {
  msg.valid = true;

Or in a Switch node first check for contains WORDB and send that to output 1, then check for starts with WORDA and send that to output 2. Set the switch to Stop after first match and connect the next node to output 2. Leave o/p 1 disconnected.

1 Like

Yes, I prefer a regex. Seems like this should be possible but I struggle some with regex... There are multiple ways to solve the problem but I am looking specifically for this regex pattern for multiple similar scenarios.

Yes, that is how I originally implemented it to get things going when I couldn’t figure out the proper regex. From a programming style standpoint, I prefer not to have switch output nodes without connections if they can be avoided. I have also encountered other scenarios where an “a and not b” regex would be useful.

I googled specific to just node-red initially but just now tried ‘regex for a and not b’ and found several examples I need to try.

Regex's aren't good at negative assertions. You will be much better off with Steve's suggestion.

1 Like

I need to do more testing but this appears to work:

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