Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for exponential function (e^x)

Tags:

java

regex

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.

like image 681
bob dylan Avatar asked Jul 06 '26 18:07

bob dylan


1 Answers

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

like image 190
Wiktor Stribiżew Avatar answered Jul 08 '26 20:07

Wiktor Stribiżew