Imamadmad
Imamadmad

Reputation: 77

Match pattern unless match is an empty string

I have a RegEx in Java that seems to work in all instances with content, however it is not just matching instances with content; it is also matching empty strings. Because of the data I'm matching, all "sections" of the RegEx must be optional, however there is no way that I know of to specify that if one section doesn't exist, the other section must exist, and vice versa (most of the time, both sections exist).

My current RegEx: (-?[0-9]*)(x\\^?([0-9]*))?

To repeat, this is working when it is matching existing characters. I just want to prevent it from matching an empty string between characters, which is throwing off the rest of my method.

Edit: Specific test string I'm using: "4x^5+x^4+2x^3-16x^2+3x-1000"

Upvotes: 0

Views: 199

Answers (1)

alpha bravo
alpha bravo

Reputation: 7948

try this pattern

(?=[0-9x-])((?:-?[0-9]*)(?:x\\^?(?:[0-9]*))?)

by adding a look-ahead (?=[0-9x-]) that must match something from your criteria
Demo

Upvotes: 1

Related Questions