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/