我有一个 Java 程序,它逐行遍历文件,并尝试将每一行与四个正则表达式之一进行匹配。根据匹配的表达式,程序执行特定操作。这是我所拥有的:
private void processFile(ArrayList<String> lines) {
ArrayList<Component> Components = new ArrayList<>();
Pattern pattern = Pattern.compile(
"Object name\\.{7}: (.++)|"
+ "\\{CAT=([^\\}]++)\\}|"
+ "\\{CODE=([^\\}]++)\\}|"
+ "\\{DESC=([^\\}]++)\\}");
Matcher matcher;
// Go through each line and see if the line matches the any of the regexes
// defined
Component currentComponent = null;
for (String line : lines) {
matcher = pattern.matcher(line);
if (matcher.find()) {
// We found a tag. Find out which one
String match = matcher.group();
if (match.startsWith("Obj")) {
// We've got the object name
if (currentComponent != null) {
Components.add(currentComponent);
}
currentComponent = new Component();
currentComponent.setName(matcher.group(1));
} else if (currentComponent != null) {
if (match.startsWith("{CAT")) {
currentComponent.setCategory(matcher.group(2));
} else if (match.startsWith("{CODE")) {
currentComponent.setOrderCode(matcher.group(3));
} else if (match.startsWith("{DESC")) {
currentComponent.setDescription(matcher.group(4));
}
}
}
}
if (currentComponent != null) {
Components.add(currentComponent);
}
}
如您所见,我已将四个正则表达式合二为一,并将整个正则表达式应用于该行。如果找到匹配项,我会检查字符串的开头以确定匹配的表达式,然后从组中提取数据。如果有人对运行代码感兴趣,下面提供了一些示例数据:
Object name.......: PMF3800SN
Last modified.....: Wednesday 9 November 2011 11:55:04 AM
File offset (hex).: 00140598 (Hex).
Checksum (hex)....: C1C0 (Hex).
Size (bytes)......: 1,736
Properties........: {*DEVICE}
{PREFIX=Q}
{*PROPDEFS}
{PACKAGE="PCB Package",PACKAGE,1,SOT-323 MOSFET}
{*INDEX}
{CAT=Transistors}
{SUBCAT=MOSFET}
{MFR=NXP}
{DESC=N-channel TrenchMOS standard level FET with ESD protection}
{CODE=1894711}
{*COMPONENT}
{PACKAGE=SOT-323 MOSFET}
*PINOUT SOT-323 MOSFET
{ELEMENTS=1}
{PIN "D" = D}
{PIN "G" = G}
{PIN "S" = S}
尽管我的代码有效,但我不喜欢稍后在调用startsWith 例程时重复部分字符串的事实。
我很想知道其他人会如何写这个。
阿米尔