[英]extract a double or integer from a string using regular expression in java?
我想從字符串中提取方程常數(即整數或雙NOT,后跟一個類似“ x”的字母)。 例如eqn = "30.14x^2 + 55.69x + 60.1 = 100"
。 到目前為止,我可以使用來獲得x
的系數
([\\+\\-])?(\\d+(\\.\\d+)?)x
在這種情況下為55.69x or 30.14x
。
現在我想獲取常量,我已經嘗試過下面的正則表達式來提取+60.1或100
(?<!^)([\\+\\-])?(\\d+(\\.\\d+)?)(?!x)
但這是行不通的,因為我已經做了一個月左右的時間,所以任何幫助將不勝感激。
關於什么
(?<!\^)(-|\+)?[\d.]++(?!x)
?
此變體使用所有格修飾符(“ ++”),對於無效數字可能不太嚴格,但是如果字符串在語法上是正確的,則沒關系。
這應該工作:
([\\+\\-])?(\\d+(\\.\\d+)?)(?![\\d.x])
[\\\\dx]
之所以有效,是因為它消除了部分數字。 例如:對於30.14x,30.14不匹配(?!x)
但匹配30.1。
這是通過兩次傳遞來提取這些值的方法:
public static void main(String[] args) {
String eqn = "30.14x^2 + 55.69x + 60.1 = 100";
String numberRegex = "[\\d]+(?:[\\.]{1}[\\d]+)?";
String symbolsRegex = "=+-/\\\\*\\^";
String coefRegex = "("+numberRegex+")([a-z]{1})";
Pattern p = Pattern.compile(coefRegex);
Matcher m = p.matcher(eqn);
while (m.find()) {
System.out.println("coefficient: " + m.group(1) + " -- " + m.group(2));
}
String constRegexp = "([^ " + symbolsRegex + "]" + numberRegex + "(?:[ ]{1}|$))";
p = Pattern.compile(constRegexp);
m = p.matcher(eqn);
while (m.find()) {
System.out.println("constant: " + m.group(1));
}
}
輸出:
coefficient: 30.14 -- x
coefficient: 55.69 -- x
constant: 60.1
constant: 100
只是添加我上面使用的正則表達式的文字值:
String coefRegex = "([\\d]+(?:[\\.]{1}[\\d]+)?)([a-z]{1})";
String constRegexp = "([^ =+-/\\\\*\\^][\\d]+(?:[\\.]{1}[\\d]+)?(?:[ ]{1}|$))";
正則表達式的問題在於您沒有對^
轉義,因此它意味着字符串的開頭。 而且,您也沒有考慮到以數字或小數點開頭的子字符串。 沒有一個人繼續前進。 因此,您的正則表達式的正確形式為:
(?<!(\\^|\\d|\\.))[+-]?(\\d+(\\.\\d+)?)(?!(x|\\d|\\.))
可以的。 而且,如果您關心x上的指數,您可能想要這樣做:
([+-])?(\\d+(\\.\\d+)?)x(^(\d+))?
順便說一下,你不需要逃避+
內[]
並且-
當它旁邊的[
的]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.