簡體   English   中英

如何從字符串中提取數字

[英]How to extract numbers from a string

String a = "sin(23)+cos(4)+2!+3!+44!";
a.replaceAll("\D"); //Not working it is only extracting Digits 

我想提取其中的數字! 僅(示例23 ),然后必須將其保存在int[]並且必須再次將這些數字粘貼到2!的位置2! 3! 存在。

第一件事:字符串是不可變的 您嘗試的代碼應該更像

a = a.replaceAll("\\D",""); 

其次,如果您確定不會有像((1+2)!+3)!這樣的更復雜的表達式((1+2)!+3)! 那么您可以使用Matcher類中的appendReplacementappendTail方法。

String a = "sin(23)+cos(4)+2!+3!+44!";

StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile("(\\d+)!");
Matcher m = p.matcher(a);
while(m.find()){
    String number = m.group(1);//only part in parenthesis, without "!"
    m.appendReplacement(sb, calculatePower(m.group(number )));
}
m.appendTail(sb);
a = sb.toString();

使用正則表達式查找所需內容:

String a = "sin(23)+cos(4)+2!+3!+44!";

Pattern pattern = Pattern.compile("\\d+!"); //import java.util.regex.Pattern
Matcher matcher = pattern.matcher(a);       //import java.util.regex.Matcher
while (matcher.find()) {
    System.out.print("Start index: " + matcher.start());
    System.out.print(" End index: " + matcher.end() + " -> ");
    System.out.println(matcher.group());
}

輸出:

Start index: 15 End index: 17 -> 2!
Start index: 18 End index: 20 -> 3!
Start index: 21 End index: 24 -> 44!

進一步改進:

使用以下代碼,可以直接使用Integer.parseInt() matcher.group(1)返回值:

Pattern pattern = Pattern.compile("(\\d+)!");
...
    System.out.println(matcher.group(1));

輸出:

Start index: 15 End index: 17 -> 2
Start index: 18 End index: 20 -> 3
Start index: 21 End index: 24 -> 44

你能找出其余的嗎? 您可以使用索引值替換原始字符串中的匹配項,但請確保從最后一個開始。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM