我在排除“#”符号之后的部分字符串时遇到一些困难。
我更好地解释自己:
这是用户可以在文本框中插入的示例输入文本:
Some Text
Some Text again #A comment
#A comment line
Another Text
Another Text again#Comment
我需要阅读此文本并忽略“#”符号之后的所有文本。
这应该是预期的输出:
Some Text;Some Text again;Another Text;Another Text again
目前代码如下:
这会将所有换行符替换为“;”
readText = userInputTextArea.getText();
readTextAllInALine = readText.replaceAll("\\n", ";");
所以之后的输出是:
Some Text;Some Text again #A comment;#A comment line;Another Text;Another Text again#Comment
此代码将忽略第一个“#”之后的所有字符,但如果我们按顺序读取全部内容,则仅适用于第一行。
int startIndex = inputCommandText.indexOf("#");
int endIndex = inputCommandText.indexOf(";");
String toBeReplaced = inputCommandText.substring(startIndex, endIndex);
readTextAllInALine.replace(toBeReplaced, "");
我一直在寻找一种获得预期输出的方法。我正在考虑使用 StringTokenizer,处理每一行,删除“#”后的文本,或者忽略以“#”开头的整行,然后打印所有标记(即所有行),并用“;”分隔它们。但我无法让它发挥作用。
任何帮助将不胜感激。
提前非常感谢您。
问候。
最佳答案
只需对从文本输入中检索的纯字符串调用此替换命令即可。正则表达式 #[^;]* 抓取所有内容,从哈希值开始,直到读取分号。然后它用空字符串替换它。
public static void main(String[] args) {
String text = "Some Text;Some Text again #A comment;#A comment line;Another Text;Another Text again#Comment";
System.out.println(text);
text = text.replaceAll("#[^;]*", "");
System.out.println(text);
}
关于JAVA - 忽略包含 "#"的部分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22151127/