I am creating a JTextField that instantly changes an underscore followed immediately by a number, to a subscript. I need help with the regex code involving replaceAll. I have read a little about regex groups, but I don’t fully understand how to get the number after the underscore in this case.
Subscript code:
// 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];
}
Insert Update Code:
public void insertUpdate(DocumentEvent e) {
if (textField.getText().contains("_"))
{
SwingUtilities.invokeLater(this);
}
}
Where the actual replace goes (since you can’t directly edit a textfield in the DocumentListener method:
public void run()
{
textField.setText(textField.getText().replaceAll("_([0-9])+", getSubscript(Integer.getInteger("$1"))));
}
This throws a NullPointer exception in the run() method.
Edit:
Here is some example output:
User types “H_2” and immediately this becomes “H₂”, then he continues “H₂O_2” which immediately becomes “H₂O₂”
You can’t do this only using
.replaceAll(). You needPatternandMatcheras follow: