求大佬回答下,就是希望能去除字符串两头的换行符,因为对正则不熟悉使用我试了下通过while判断字符串是否以换行符开头结尾,然后通过substring的方法一点点截,不管好像结果有问题,这个问题卡了我一个晚上了,好头疼。
最好是java实现_(:з」∠)_
直接上代码,不懂回复
private static final char CHARS = ' ';//记录空格常量
public static void main(String[] args)
{
String time = " ejpo ijimlo ";
int s = 0;
int e = time.length()-1;
while(s < time.length() && time.charAt(s) == CHARS){ //用charAt方法,指定角标看是否有‘ ’
s++;
}
while (s <= e && time.charAt(e) == CHARS){ //开始位置<=结尾位置,反则就可能有‘ ’
e--;
}
String ot = time.substring(s,e+1);
System.out.print(ot);
System.out.print(">>>");//区分下结尾是否有空格
}
public static String trim(char[] value) {
int len = value.length;
int st = 0;
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[st] <= '\n')) {
st++;
}
while ((st < len) && (val[len - 1] <= '\n')) {
len--;
}
return ((st > 0) || (len < value.length)) ? substring(String.valueOf(value), st, len) : String.valueOf(value);
}
用 java自己写的一个实现即可仅去除首位的任意符号
收尾包含 \n 的正则表达式为:
String pattern = "^\\n[\\s\\S]+\\n$";
String h = "\nhelload\n";
System.out.println(h.matches(pattern));// true
h = "\nhelload";
System.out.println(h.matches(pattern));// false