3

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.

1
  • 1
    [+|-]?\d*e\^[+|-]?\d*x?
    – Uma Kanth
    Dec 31, 2015 at 12:58

6 Answers 6

4

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

3

The problem is that ^ symbol is for the start of the string and hence if you want to use if only for the symbol at / before it.

2

-?\\d*\\.?\\d*e\\^-?\\d*\\.?\\d*x works for floating point numbers as well.

It matches:

  • e^x
  • -3e^x
  • 100e^-x
  • e^-2x
  • -0.1e^2x
  • -0.1e^0.2x
0

your required regex will be like this the basic problem is with your regex is ^ sign you have to ignore ^ as like start match use \^

e\^-?\d*?

and your code will be

if(str.matches("e\^\-?\d*?") ){
            System.out.println("match");
}
0
-?\\d*\\.?\\d*e\\^-?\\d*\\.?\\d*x
-1

It should work for -?\\d*e\\^-?\\d*x

-? matches the character - literally, Quantifier: ? Between zero and one time

\d* match a digit [0-9] Quantifier: * Between zero and unlimited times

e matches the character e literally (case sensitive)

\^ matches the character ^ literally

-? matches the character - literally, Quantifier: ? Between zero and one time

\d* match a digit [0-9] Quantifier: * Between zero and unlimited times

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.