通过正则表达式提取两个组号

时间:2017-12-03 19:57:49

标签: java android regex

我有以下字符串,我想通过在java(android studio)中使用正则表达式从中提取150和136,这两个数字都在MB之前(它们之间存在空间)有时候第二个数字不存在我怎么能提取它们 分开组?

"Your Day Traffic is 150 MB and your Night Traffic is 136 MB "

给我两个这样的小组:

group 1 ==> "150"
group 2 ==> "136"

最佳答案:

经过一些搜索并在egex101.com上尝试后,我找到了答案:

    Pattern p = Pattern.compile("^[^\\d]*(\\d+(?:\\.\\d+)?) MB(?:[^\\d]+(\\d+(?:\\.\\d+)?) MB)?.*$");//. represents single character
    Matcher m = p.matcher("Your Day Traffic is 150 MB and your Night Traffic is 136 MB");

    while (m.find()) {
        System.out.println("group 1 ==>" + m.group(1));
        System.out.println("group 2 ==>" + m.group(2));
    }

我明白了:

group 1 ==>150
group 2 ==>136

2 个答案:

答案 0 :(得分:2)

如果号码与((\d+)\sMB)之间有一个或多个空格可以使用MB来匹配一个或多个空格,则可以使用此正则表达式\s+,您可以执行以下所有操作图案

String text = "Your Day Traffic is 150 MB and your Night Traffic is 136 MB ";
String regex = "((\\d+)\\sMB)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
int group = 1;
while (matcher.find()) {
    System.out.println("group " + group++ + " ==> " + matcher.group(2));
}

在您的情况下输出是:

group 1 ==> 150
group 2 ==> 136

答案 1 :(得分:0)

请阅读正则表达式here上的java文档。

基本上你必须忽略两个“[数字] MB”出现之间的字符。在这种情况下,您可以使用像这样的正则表达式 -

/.*\s+(\d+)\s+MB.*\s+(\d+)\s+MB/

这里给出了完整的代码 -

import java.util.regex.*;  

public class MatchMB {  
  public static void main(String args[]){  
  Pattern p = Pattern.compile(".*\\s+(\\d+)\\s+MB.*\\s+(\\d+)\\s+MB");  
  Matcher m = p.matcher("Your Day Traffic is 150 MB and your Night Traffic is 136 MB");  

  while (m.find()) {
    System.out.println("group 1 ==>" + m.group(1));
    System.out.println("group 2 ==>" + m.group(2));
  }
}