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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With