我有一个像这样的字符串表达式:
(code name credits) or ((code name credits) and (code name credits))
我想识别字符串中的所有(代号名称)组合,并将它们替换为一个值。
代码是字母和数字的组合。
名称是单词的组合,用一个空格分隔,单词可以同时包含字母和数字。
信用是一个数字。
每个组件均由制表符分隔。
(代号学分)组合的实际示例如下:
IABIG-02 Computer Graphics 5
这与问题无关,但这就是我想要实现的目标:
输入:
(IABIG-02 Computer Graphics 5) or ((AIBJH88 Computer Vision 5) and (AIKKH10 Computer Architecture 5))
输出:
T or (F and T)
最佳答案
这是一种可能的方法,我找不到任何干净的方法来实现它:
String value = "(IABIG-02\tComputer Graphics\t5) or ((AIBJH88\tComputer Vision\t5) and (AIKKH10\tComputer Architecture\t5))";
Pattern pattern = Pattern.compile("\\((\\w|-)+\\t\\w+( \\w+)*\\t\\d\\)");
Matcher matcher = pattern.matcher(value);
StringBuilder builder = new StringBuilder(value.length());
Map<String, Character> replacements = new HashMap<>();
char c = 'A';
int index = 0;
while (matcher.find(index)) {
builder.append(value, index, matcher.start());
String found = matcher.group();
Character replacement = replacements.get(found);
if (replacement == null) {
replacement = c++;
replacements.put(found, replacement);
}
builder.append(replacement);
index = matcher.end();
}
if (index < value.length()) {
builder.append(value, index, value.length());
}
System.out.println(builder);
输出:
A or (B and C)
它用从 A
开始的替换字符替换找到的所有模式。我使用 Map
是为了能够重用之前赋予相同模式的字符。
关于java - 如何在Java字符串表达式中查找字符串模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36795657/