How to combine RegEx conditions?

389 Views Asked by At

I need to make a QLineEdit with a QRegularExpressionValidator with the following 3 constraints:

  1. Cannot start with empty space ^[\\S]
  2. Cannot start with Hello ^(?!Hello).+
  3. Cannot end with empty space ^.*[\\S]$

How do I combine those 3 in one regex so that I can set it a QRegularExpressionValidator?

Thank you!

Note: As long as I have a regex that is verifiable with a regex tool I am good. I have specified Qt just to provide more context.

2

There are 2 best solutions below

0
On BEST ANSWER

You could use

^(?!Hello\b)\S(?:.*\S)?$

Explanation

  • ^ Start of string
  • (?!Hello\b) Negative lookahead, assert what is directly to thte right is not Hello
  • \S Match a non whitespace char
  • (?:.*\S)? Optionally match 0+ times any char except a newline and a non whitespace char
  • $ End of string

Regex demo

9
On

This should do it:

var strings = [
  'a',
  'this is ok',
  ' leading space',
  'trailing space ',
  'Hello text',
  'Hello'
];
var re = /^([^\s]|(?!(Hello|\s)).*[^\s])$/;
strings.forEach((str) => {
  var val = re.test(str);
  console.log('"' + str + '" ==> ' + val);
});

Console output:

"a" ==> true
"this is ok" ==> true
" leading space" ==> false
"trailing space " ==> false
"Hello text" ==> false
"Hello" ==> false

Explanation of the regex:

  • ^...$ -- anchor at the beginning and end
  • ([^\s]|...) -- logical or, where the first part is a single non space char
  • (?!(...)).+ -- negative lookahead
  • (Hello|\s) -- ... of 'Hello' or space
  • .+[^\s] -- followed by any number of chars, except space at the end