bob dylan bob dylan - 4 years ago 147
Java Question

Java: Regex for e^x

I am trying to check if a string contains something with

e^x
or
e^(any #, including negative)x
, but I can't quite figure it out. Here is what I have tried:

if(str.matches("^(e^x)$") || str.matches("^(e^[-?0-9]x)$")){
System.out.println("match");
}


Some examples that would match would be:

-3e^x
100e^-x
e^-2x


I have referenced this, but I still can't figure it out.

Answer Source

Unescaped ^ matches the beginning of a string. If you use it inside the regex pattern and do not specify the multiline flag, the pattern will always fail since a start of a string cannot appear in the middle of it.

You need to escape the ^ and with matches() you do not need anchors. Also, you can just use ? (one or zero occurrences) or * (zero or more occurrences) quantifiers:

if(str.matches("-?[0-9]*e\\^-?[0-9]*x"))

See the regex demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download