我正在开发WebView控制台,我想使用正则表达式来检测字符串中的颜色代码。我有一个表达:
(&(?<colorIndex>d|[eadfcblmor]))?(?<text>[^(&d|[eadfcblmor])]+)
仅当颜色索引后跟文本时,它才匹配。例:
&1Hello &2World&1!
("Hello"是蓝色的,"World"是绿色的,"!"是蓝色的)
我想在文本中添加格式(粗体、斜体等),因此当 colorIndex 后跟没有文本时,我需要检测格式更改。例:
&1Hello &l&2World &r&1&!
("Hello"是蓝色的,"World"是粗体和绿色的,"!"是正常的和蓝色的)
但是我"&l&2World"只是被着色,因为"§l"后面没有文本。
在表达式中更改什么才能做到这一点?
谢谢,对不起我的英语不好!
编辑:
WebViewConsole.class:
public class WebViewConsole {
WebView console;
String contentHtml = "";
Pattern pattern = Pattern.compile("(&(?<colorIndex>\d|[eadfcblmor]))?(?<text>[^(&\d|[eadfcblmor])]+)");
char[] colors = {'1', '2', '3', '4', '5', '6', '7', '8', '9', 'e', 'a', 'd', 'f', 'c', 'b'};
String[] formats = {"o", "l", "m"};
public WebViewConsole() {
console = new WebView();
}
public List<String> getHtmlFormat(String text) {
List<String> formats = new ArrayList<>();
String color = "white";
String format = "normal";
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
String codeInText = matcher.group("colorIndex");
String textInText = matcher.group("text");
if (codeInText != null/* && codeInText.matches("\d|[eadfcblmor]+")*/) {
if (isFormat(codeInText)) {
format = getFormatName(codeInText);
} else {
color = getFormatName(codeInText);
}
} else {
color = "white";
format = "normal";
}
if (codeInText != null && codeInText.matches("\d|[eadfcblmor]+")) {
formats.add("<span style="color:" + color + ";font-weight:" + format + "">" + textInText + "</span>");
}
}
return formats;
}
public void appendText(String text) {
for (String htmlText : getHtmlFormat(text)) {
contentHtml += htmlText.replaceAll("\n", "<br>");
}
//contentHtml += "<br>";
getConsole().getEngine().loadContent(contentHtml);
}
public WebView getConsole() {
return console;
}
public boolean isFormat(String code) {
if (!code.equalsIgnoreCase("r")) {
for (String format : formats) {
if (format.equals(code)) {
return true;
}
}
}
return false;
}
public String getFormatName(String code) {
switch (code) {
case "1":
return "blue";
case "2":
return "darkgreen";
case "l":
return "bold";
case "o":
return "bold";
}
return null;
}
public void clear() {
contentHtml = "";
getConsole().getEngine().loadContent(contentHtml);
}
}
我在一点帮助下找到了解决方案。
我将正则表达式从:
(&(?<colorIndex>d|[eadfcblmor]))?(?<text>[^(&d|[eadfcblmor])]+)
自:
(&(?<colorIndex>d|[eadfcblmor]))?(?<text>[^(&d|[eadfcblmor])]*)