Intrinsic
Intrinsic

Reputation: 59

Regular Expression negation not working correctly

I am using the following regular expression:

^[^^DD(|    ]

With this data:

jfklajf
^DD
     hjhkjk
DIOL(.D1)

The expression correctly identifies the first line (jfkl...), but fails to identify the last line (DIOL...). I need to identify both lines as not matching the pattern ^DD( at the start of the line.

What am I doing wrong?

Thanks

Upvotes: 2

Views: 47

Answers (5)

Jan
Jan

Reputation: 43199

As per your comment you could use a neg. lookahead in combination with anchors:

^(?!\^DD|[ ]{4}).+


Broken down, this says:

^          # match start of the line
(?!        # neg. lookahead
    \^DD   # neither ^DD
    |      # nor
    [ ]{4} # four spaces
)
.+         # omit empty lines

See a demo on regex101.com. Note that you need to double escape backslashes in Java.

Upvotes: 4

meles
meles

Reputation: 456

^((?![^DD|\s{4}]).)

Explanation

^...Start of the line
((?!Expression).)...not matching
[^DD|\s{4}]...Pattern 1 (^DD) or Pattern 2 (\s{4})
\s{4}...whitespaces 4 times

Upvotes: 0

Tensibai
Tensibai

Reputation: 15784

Your regex is saying : as sentence not starting with ^, D, (, | or space.

[] construct is a character class meaning it will match any one character from the class, starting the class with ^ negates it and means any one character not in the class.

As stated in the others answers you should look for a negative lookahead or if you like complexity and I understand your try well:

^([^^][^D]{2}[^(]|[^ ]{4})

Upvotes: 0

kfairns
kfairns

Reputation: 3067

Perhaps:

(?!^\^DD|^\s+)^.+$

See the demo

Yours is currently attempting to match any character in this list:

D, , (, |

Using a group construct instead of the character list (square brackets), you'll have more luck

Upvotes: 0

Chris Lear
Chris Lear

Reputation: 6752

You need a negative lookahead. Something like this

^(?!((\^DD)|(    )))

See https://regexr.com/3ke44

Upvotes: 1

Related Questions