我需要替换文本区域中的最后一个单词,可能使用文档过滤或在 lastword 和 beforelastword 之间使用空格跨度(“”)。有人能帮助我吗?我在谷歌搜索仍然没有找到方法。import java.awt.BorderLayout;import java.awt.EventQueue;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.UIManager;import javax.swing.UnsupportedLookAndFeelException;import javax.swing.event.DocumentEvent;import javax.swing.event.DocumentListener;import javax.swing.text.Utilities;public class TheLastWord { public static void main(String[] args) { new TheLastWord(); } public TheLastWord() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new TestPane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); }
2 回答
拉风的咖菲猫
TA贡献1995条经验 获得超2个赞
你可以分开。并获取最后一个索引,然后像这样插入子字符串
String sentence ="Meow test test hello test.";
String[] temp = sentence.split("[|!|\\?|.|\\s|\\n]");
String word = temp[temp.length-1];
int index = sentence.lastIndexOf(word);
String out = sentence.substring(0,index) + " INSERTED WORD" + sentence.substring(index+word.length(), sentence.length());
胡说叔叔
TA贡献1804条经验 获得超8个赞
您可以使用像这样的正则表达式(\w+.?)$,它会匹配字符串的最后一个单词,即使它以..
String sentence = "I am a full sentence";
String replaced = sentence.replaceAll("(\\w+.?)$", "replaced");
System.out.println(replaced); // prints 'I am a full replaced'
添加回答
举报
0/150
提交
取消