簡體   English   中英

正則表達式,用於分割字符串中的雙整數和整數

[英]Regular Expression to split double and integer numbers in a string

我需要一個正則表達式來分隔字符串的整數和雙元素,如下例所示:

String input = "We have the number 10 and 10.3, and i want to split both";
String[] splitted = input.split(/*REGULAR EXPRESSION*/);
for(int i=0;i<splitted.length;i++)
    System.out.println("[" + i + "]" + " -> \"" + splitted[i] + "\"");

輸出將是:

  • [0] - >“我們有號碼”
  • [1] - >“10”
  • [2] - >“和”
  • [3] - >“10.3”
  • [4] - >“,我想分開兩個”

有人能幫我嗎? 我會很感激。

您需要將這些塊與以下內容匹配

\D+|\d*\.?\d+

請參閱正則表達式演示

細節

  • \\D+ - 除數字以外的1個或更多字符
  • | - 要么
  • \\d*\\.?\\d+ - 一個簡單的整數或浮點數(可能會增強到[0-9]*[.]?[0-9]+(?:[eE][-+]?[0-9]+)?來源

Java演示

String s = "We have the number 10 and 10.3, and i want to split both";
Pattern pattern = Pattern.compile("\\D+|\\d*\\.?\\d+");
Matcher matcher = pattern.matcher(s);
List<String> res = new ArrayList<>();
while (matcher.find()){
    res.add(matcher.group(0)); 
} 
System.out.println(res); 

暫無
暫無

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

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