簡體   English   中英

在Java中的括號處分割字符串

[英]Splitting string at parentheses in Java

現在,如果我有一個像這樣的字符串:

String start = "(1374)(48.4%)(32)(100%)(290)(43.1%)";

如何提取六個數字1374 48.4 32 100 290 43.11374 48.4% 32 100% 290 43.1% 可以用正則表達式完成嗎?

您可以搜索標識浮點數的正則表達式: ([+-]?(\\d+\\.)?\\d+)

String start = "(1374)(48.4%)(32)(100%)(290)(43.1%)";

Pattern p = Pattern.compile("([+-]?(\\d+\\.)?\\d+)");
Matcher m = p.matcher(start);
while (m.find()) {
    System.out.println(m.group(1));
}

或使用正則表達式來確保括號在其中:

Pattern p = Pattern.compile("\\(([+-]?(\\d+\\.)?\\d+)\\%?\\)");

讓我們不用正則表達式就可以做!

int i = 0;
while (i < start.length()) {
  while (i < start.length()) {
    char ch = start.charAt(i);
    // Maybe add other characters, e.g. %, if desired.
    if (Character.isDigit(ch) || ch == '.') {  
      break;
    }
    ++i;
  }
  int startOfBlock = i;
  while (i < start.length()) {
    char ch = start.charAt(i);
    if (!Character.isDigit(ch) && ch != '.') {
      break;
    }
    ++i;
  }
  if (i > startOfBlock) {
    System.out.println(start.substring(startOfBlock, i));
  }
}

或者您可以嘗試以下正則表達式[\\d\\.%]+它會為您提供包含以下項的字符串組合
\\d (數字)
\\. 點和
%符號
一或多次
單擊此處進行實時演示

    String start = "(1374)(48.4%)(32)(100%)(290)(43.1%)";
    for(String splitString : start.split("[()]")) {
        System.out.print(splitString + " ");
    }

暫無
暫無

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

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