【发布时间】:2020-10-30 06:48:02
【问题描述】:
我的字符串如下所示,字符串由换行符连接。在这个字符串中,前两行和后两行是固定的,public class FakeClass {/n public void fakeMethod() {/n
String sampleCode =
String.format(
createLines(7),
"public class FakeClass {\n",
" public void fakeMethod() {\n",
" int a = 5;\n",
" int b = 6;\n",
" a = b;\n",
" }\n",
"}\n");
);
private static String createLines(int numLines) {
return new String(new char[numLines]).replace("\0", "%s");
}
我想去掉两条前导线和两条尾随线。我可以简单地使用子字符串
String result = sampleCode.substring(53, sampleCode.length() - 5)
输出是:
assertEqual(result, String.format(
createLine(3),
" int a = 5;\n",
" int b = 6;\n",
" a = b;\n",
));
我想知道我们是否可以使用正则表达式模式匹配来删除两条前导和尾随行。
【问题讨论】:
-
能否添加预期的输出
-
由
\n分割得到一个单独的行数组,然后通过丢弃前2个元素来做一个子列表 -
只添加预期的输出。
-
@anubhava 谢谢,但我正在寻找一种使用正则表达式的方法。由
\n分割,占用另一个空间。 -
@anubhava 只是添加功能,对不起。