我正在创建一个 JTextField,它会立即将下划线后跟数字更改为下标。我需要有关replaceAll 的正则表达式代码的帮助。我读过一些有关正则表达式组的内容,但我不完全理解在这种情况下如何获取下划线后面的数字。
下标代码:
// Only 0 - 9 for now...
private String getSubscript(int number)
{
String[] sub = {"\u2080", "\u2081","\u2082","\u2083","\u2084","\u2085","\u2086","\u2087","\u2088","\u2089" };
return sub[number];
}
插入更新代码:
public void insertUpdate(DocumentEvent e) {
if (textField.getText().contains("_"))
{
SwingUtilities.invokeLater(this);
}
}
实际替换的位置(因为您无法直接在 DocumentListener 方法中编辑文本字段:
public void run()
{
textField.setText(textField.getText().replaceAll("_([0-9])+", getSubscript(Integer.getInteger("$1"))));
}
这会在 run() 方法中引发 NullPointer 异常。
编辑:
这是一些示例输出:
用户输入“H_2”,它立即变成“H2”,然后他继续输入“H2O_2”,它立即变成“H2O2”
最佳答案
仅使用 .replaceAll() 无法做到这一点
。您需要 Pattern
和 Matcher
如下:
public void run() {
String text = textField.getText();
Pattern pattern = Pattern.compile("_[0-9]+");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
// get the init string (e.g. "_42")
String group = matcher.group();
// parse it as an int (i.e. 42)
int number = Integer.valueOf(group.substring(1));
// replace all "_42" with the result of getSubscript(42)
text = text.replaceAll(group, getSubscript(number));
// recompile the matcher (less iterations within this while)
matcher = pattern.matcher(text);
}
textField.setText(text);
}
关于java - 使用replaceAll作为下标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10478409/