okay so I set up this regex to take exponential and give me back doubles but it crashes if I give it less than two
String sc = "2 e 3+ 1";
Pattern pattern = Pattern.compile("\\s+");
Matcher matcher = pattern.matcher(sc);
boolean check = matcher.find();
sc = matcher.replaceAll("");
String sc1;
Pattern p = Pattern.compile("[0-9]+[.]?[0-9]*[eE][-+]?[0-9]+");
Matcher m = p.matcher(sc);
m.find();
int starting = m.start(); //where first match starts
int ending = m.end();//where it ends
String scientificDouble = sc.substring(starting, ending);
String replacement = "" + Double.parseDouble(scientificDouble);
sc1 = sc.replace(scientificDouble, replacement); //first time
//this block must go in a loop until getting to the end, i.e. as long as m.find() returns true
m.find();
starting = m.start(); //where next match starts
ending = m.end();//where it ends
scientificDouble = sc.substring(starting, ending);
replacement = "" + Double.parseDouble(scientificDouble);
sc1 = sc1.replace(scientificDouble, replacement);//all other times,
if I give it sc = “2e3 + 1 ” it crashes saying
Exception in thread "main" java.lang.IllegalStateException: No match available
at java.util.regex.Matcher.start(Matcher.java:325)
at StringMan.main(StringMan.java:32)
To add to @Stephen C’s answer,
find()will not magically loop the block of code for you. Since you want to execute the same block of code as long asfind()returnstrue, you should use a while loop:(using regex correctly suggested by @Martijn Courteaux’s answer)
This particular example prints all parsed
doubletoSystem.out– you can do what you need with them.Please upvote the cited answers if this is helpful.