regex giving error less than 2 [closed]
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, repla开发者_开发知识库cement); //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)
Your regex doesn't fit the spaces in your string. I tried to fix your regex, try this:
Pattern p = Pattern.compile("[0-9]+(\\.[0-9]+)?[eE][\\-\\+]?[0-9]*");
String sc = "2e3+1"; // Whitespaces cleared
still crashed :Exception in thread "main" java.lang.IllegalStateException: No match available ...
That's because you are ignoring the result of the m.find(...)
calls. If m.find
returns false
, then the pattern match failed and methods like Matcher.start
Matcher.end
and Matcher.group
will throw IllegalStateException
if called.
This will all be explained in the Javadoc for Matcher
and its methods. I strongly recommend that you take the time to read it.
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 as find()
returns true
, you should use a while loop:
String source = "2e3+1, 2.1e+5, 2.8E-2";
Pattern pattern = Pattern.compile("[0-9]+(\\.[0-9]+)?[eE][\\-\\+]?[0-9]*");
Matcher matcher = pattern.matcher(source);
while (matcher.find()) {
String match = matcher.group();
double d = Double.parseDouble(match);
System.out.println(d);
}
(using regex correctly suggested by @Martijn Courteaux's answer)
This particular example prints all parsed double
to System.out
- you can do what you need with them.
Please upvote the cited answers if this is helpful.
精彩评论