正则表达式给出小于2的误差

时间:2011-09-25 06:28:45

标签: java regex

好吧所以我设置这个正则表达式取指数并给我回复双打但如果我给它少于两个就崩溃

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,

如果我给它sc =“2e3 + 1”它会崩溃说

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)

3 个答案:

答案 0 :(得分:1)

你的正则表达式不适合你的字符串中的空格。我试着修复你的正则表达式,试试这个:

Pattern p = Pattern.compile("[0-9]+(\\.[0-9]+)?[eE][\\-\\+]?[0-9]*");

String sc = "2e3+1"; // Whitespaces cleared

答案 1 :(得分:1)

  

仍然崩溃:线程“main”中的异常java.lang.IllegalStateException:无匹配可用...

那是因为你忽略了m.find(...)电话的结果。如果m.find返回false,则模式匹配失败,Matcher.start Matcher.endMatcher.group等方法会在调用时抛出IllegalStateException

这将在Matcher的Javadoc及其方法中进行解释。我强烈建议你花点时间阅读它。

答案 2 :(得分:0)

要添加到@Stephen C's answerfind()不会为您神奇地循环代码块。由于您希望在find()返回true时执行相同的代码块,因此您应该使用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);
}

(使用@Martijn Courteaux's answer正确建议的正则表达式)

此特定示例将所有已解析的double打印到System.out - 您可以随身携带它们。

如果有帮助,请提及所引用的答案。