java正则表达式,用于使用一个或多个单词作为搜索键匹配一行
假设我们有一个格式如下的字符串:
"part1 part2: part3"
part1和part2通常是一个单词(包括小写和大写字母),而part3可以是数字和字符的任意组合(包括标点符号)。此外,在:
之前或之后可以有多个空格
我将编写一个正则表达式来匹配这样的字符串。例如,如果示例字符串如下所示:
String sample1 = "Total Amount: $1,000";
String sample2 = "Company: Google Inc.";
搜索像数量、总量或总量这样的键,我想匹配样本1字符串。同时搜索一个键,比如company我想匹配sample2字符串
EDIT:
As a result, if we have a string like the sample above, by searching "Total", "Amount", or "Total Amount" we should return the sample string as a match. And, it is important that: 1) not only the line should contain the key, but it should also follow the specified format for the line and 2) user enters the key.
这是我现在的正则表达式:
String reg = "[tTOoTtAaLl0-9.,\/#!$%\^&\*;:{}=\-_`~( ) ]+:[A-Za-z0-9.,\/#!$%\^&\*;:{}=\-_`~( ) ]+";
然而,我的正则表达式与整个行不匹配。值得指出的是,我使用了Java,假设样本字符串存储在样本中,我使用sample.matches(reg)
来检查字符串是否匹配
# 1 楼答案
不确定我是否正确理解了您的要求,但根据您的数据和我猜您想要得到的,这里有两个示例:
1)仅获取美元金额的示例:https://regex101.com/r/7P2Bad/3
2)获取匹配的完整字符串的示例:https://regex101.com/r/7P2Bad/2
考虑到使用Java(与regex101.com的语法不同)regex应该转义一些字符
处理以下情况:
输出:
评论后编辑:
然后,在读了你的评论之后,你想要这样的东西:
输出:
说明:
userKey
var放入该%s占位符。格式方法