java - 使用 JTextField 从用户获取正则表达式。如何让它显示为选项卡而不是后跟 t

标签 java regex swing jtextfield

JTextField reSource; //contains the regex expression the user wants to search for
String re=reSource.getText();
Pattern p=Pattern.compile(re,myflags); //myflags defined elsewhere in code
Matcher m=p.matcher(src); //src is the text to search and comes from a JTextArea
while (m.find()==true) {
  • 如果用户输入 \t,它会发现 \t 而不是 Tab。
  • 如果用户输入 \\\t,则会发现 \\\t 而不是 Tab。
  • 如果用户输入 [\t][\\\t],则会发现 t 而不是 Tab。

我希望这样,如果用户输入 \t 它会找到选项卡。当然它还需要与 \n\r 等一起使用...

如果使用 re="\t"; 而不是 re=reSource.getText();,并且 \t 位于 JTextField 然后它会找到选项卡。如何让它与 JTextField 的内容一起工作?

最佳答案

示例:

String src = "This\tis\ta\ttest";
System.out.println("src=\"" + src + '"'); // --> prints "This is a test"
String re="\\t";
System.out.println("re=\"" + re + '"'); // --> prints "\t" - as when you use reSource.getText();

Pattern p = Pattern.compile(re);
Matcher m = p.matcher(src);
while (m.find()) {
    System.out.println('"' + m.group() + '"');
}

输出:

src="This   is  a   test"
re="\t"
"   "
"   "
"   "

试试这个:

re=re.replace("\\t", "\t");
OR
re=re.replace("\\t", "\\\\t");

我认为问题在于理解当你输入时:

String str = "\t";

那么它实际上与:

String str = "   ";

但是如果你输入:

String str = "\\t";

那么System.out.print(str)将是"\t"

关于java - 使用 JTextField 从用户获取正则表达式。如何让它显示为选项卡而不是后跟 t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9193335/

相关文章:

c++ - RegEx 获取两个换行符之间的文本

java - 在 JFrame 上定位组件

java - 计算相同起点和终点之间的距离

java - 日期格式 JSON

第一个括号之间的 Javascript 正则表达式字符串,包括括号内

javascript - 使用具有大括号的正则表达式获取字符串的匹配项并替换所有包含大括号的内容

java - 选择复选框时如何从 jtable 和数据库中删除一行?

java - 在 Model-View-Controller 中,为什么模型的改变不会触发 View 的改变?

java - 无法获取数组中的其余数字。 java

java - 重载冲突