【问题标题】:Reg exp: extract FIRST number from text正则表达式:从文本中提取第一个数字
【发布时间】:2021-01-21 11:24:16
【问题描述】:

我只是不知道如何从 Textview 中提取第一个数字。

我的 Textview 是

"Maximum week limit of this debit card is 300 000 CZK. Limit can be still increased up to 265 944 CZK".

我需要从这个对象中提取 300 000 个数字。

我可以很容易地找到这个 Textview 的 ID 并使用它。可以请人帮助我吗?谢谢。

【问题讨论】:

标签: regex testing automation text-parsing


【解决方案1】:

您可以使用正则表达式方法:

String input = "Maximum week limit of this debit card is 300 000 CZK. Limit can be still increased up to 265 944 CZK";
String firstNum = input.replaceAll("^.*?(\\d[0-9 ]*).*$", "$1");
System.out.println("First number is: " + firstNum);

打印出来:

First number is: 300 000

这里的策略是使用正则表达式来捕获第一个数字。逻辑如下:

^                 from the start of the string
    .*?           match all content up to, but not including, the first digit
    (\\d[0-9 ]*)  then match and capture any number of digits or space separators
    .*            match the rest of the input
$                 end of the input

【讨论】:

  • 这对我不起作用,这是我的代码:String str = limit.getText(); //gets the string str.replaceAll("^.*?(\\d[0-9 ]*).*$", "$1"); //keeps only the first number limitsPOSValue.clear();//clears the object i want to put the value in limitsPOSValue.sendKeys(str);//sends the first number to the object 错误只是说我不能把整个句子放在那里,所以它只是没有只保留第一个数字
  • 然后编辑您的问题并包括我的回答失败的边缘情况。
【解决方案2】:

参考:https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html 在这里你可以测试你的正则表达式https://regexr.com/

    final String REGX1 = "([0-9]+ [0-9]+)";
    final String REGX2 = "([0-9]+)";
    String sample = "Maximum week limit of this debit card is 300 000 CZK. Limit can be still increased up to 265 944 CZK";
    
    Pattern pattern1 = Pattern.compile(REGX1);
    Pattern pattern2 = Pattern.compile(REGX2);
    
    Matcher pm1 = pattern1.matcher(sample);
    Matcher pm2 = pattern2.matcher(sample);
    
    System.out.println("1. REGX");
    System.out.println("--------------------------------");
    int index = 1;
    while(pm1.find())
    {
        System.out.println(index+". "+pm1.group(0));
        index++;
    }
    
    System.out.println("--------------------------------");
    System.out.println("2. REGX");
    System.out.println("--------------------------------");
    
    index = 1;
    while(pm2.find())
    {
        System.out.println(index+". "+pm2.group(0));
        index++;
    }

Output

1. REGX
--------------------------------
1. 300 000
2. 265 944
--------------------------------
2. REGX
--------------------------------
1. 300
2. 000
3. 265
4. 944

【讨论】:

    猜你喜欢
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    相关资源
    最近更新 更多