我需要在一个字符串中找到一个特定的模式并从中提取一个子字符串。例如字符串:
{'Opening Cost P&L per store','Opening Costs Capital per store','Average Monthly Revenue','GROSS MARGIN %'}] = N:DB('Store Cost',
!Country and Region, DB('New Store Plan', !Country and Region,
!ID numbers, !Budget version, 'Retailer Type'), ATTRS('New Stores',
!New Stores, '}Map_}Link_New Store Plan_3CStore Cost'), DB('New Store Plan',
!Country and Region, !ID numbers, !Budget version, 'Size'),
DB('New Store Plan', !Country and Region, !ID numbers, !Budget version,
'Franchise/Corporate'), 'DATA')
我必须搜索:
DB('
only,而不是其他模式,例如S:DB('
or DB('}
。
然后在找到此模式后,我必须在列表中获取文本,该列表在此模式之后可用,并且仅在引号中,例如
DB('Metrics cube-HumanResource', !country, !Time, !gometric, !Metric Indicators), CONTINUE)
DB('Metrics cube-InternalProcess', !country, 'Total of Product', !Time, !gometric, !Metric Indicators), CONTINUE);
那么输出将是:
1 - Metrics cube-HumanResource
2 - Metrics cube-InternalProcess
这是我的代码。但它不打印任何东西:
public class StringRegex {
public static void main(String[] args) {
String str = "{'Opening Cost P&L per store','Opening Costs Capital per store','Average Monthly Revenue','GROSS MARGIN %'}] = N:DB('Store Cost', \n" +
" !Country and Region, DB('New Store Plan', !Country and Region, \n" +
" !ID numbers, !Budget version, 'Retailer Type'), ATTRS('New Stores', \n" +
" !New Stores, '}Map_}Link_New Store Plan_3CStore Cost'), DB('New Store Plan', \n" +
" !Country and Region, !ID numbers, !Budget version, 'Size'), \n" +
" DB('New Store Plan', !Country and Region, !ID numbers, !Budget version, \n" +
" 'Franchise/Corporate'), 'DATA')";
String[] strArray = str.split(",");
for(String s : strArray){
if(s.matches("DB\\('.+'")){
System.out.println(s);
}
}
}
}
我会使用 aPattern
和 aMatcher
而不是拆分String
. 你会更容易得到结果。使用以下正则表达式:
.*?[^:]DB\((.*?)\).*?
这将捕获每个 DB(.*) 的内容,而不是以:
. 使用惰性量词*?
将防止出现问题,例如在右括号之前捕获的不仅仅是文本。
从Regex101:
String regex = ".*?[^:]DB\\((.*?)\\).*?";
String string = "{'Opening Cost P&L per store','Opening Costs Capital per store','Average Monthly Revenue','GROSS MARGIN %'}] = N:DB('Store Cost', \n"
+ " !Country and Region, DB('New Store Plan', !Country and Region, \n"
+ " !ID numbers, !Budget version, 'Retailer Type'), ATTRS('New Stores', \n"
+ " !New Stores, '}Map_}Link_New Store Plan_3CStore Cost'), DB('New Store Plan', \n"
+ " !Country and Region, !ID numbers, !Budget version, 'Size'), \n"
+ " DB('New Store Plan', !Country and Region, !ID numbers, !Budget version, \n" + " 'Franchise/Corporate'), 'DATA')";
Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.DOTALL);
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("> " + matcher.group(1));
}
结果 :
> 'New Store Plan', !Country and Region,
!ID numbers, !Budget version, 'Retailer Type'
> 'New Store Plan',
!Country and Region, !ID numbers, !Budget version, 'Size'
> 'New Store Plan', !Country and Region, !ID numbers, !Budget version,
'Franchise/Corporate'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句