如何解决Reg exp:从文本中提取第一个数字
我的文本视图是
"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 并使用它。请有人帮助我吗?谢谢。
解决方法
您可以使用正则表达式方法:
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
,
参考: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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。