[英]Trim whitespaces
我知道String的trim()函數,我想自己實現它以更好地了解正則表達式。 以下代碼似乎在Java中不起作用。 任何輸入?
private static String secondWay(String input) {
Pattern pattern = Pattern.compile("^\\s+(.*)(\\s$)+");
Matcher matcher = pattern.matcher(input);
String output = null;
while(matcher.find()) {
output = matcher.group(1);
System.out.println("'"+output+"'");
}
return output;
}
輸出為
input = " This is a test " is 'This is a test '
我可以使用其他方式來做到這一點
private static final String start_spaces = "^(\\s)+";
private static final String end_spaces = "(\\s)+$";
private static String oneWay(String input) {
String output;
input = input.replaceAll(start_spaces,"");
output = input.replaceAll(end_spaces,"");
System.out.println("'"+output+"'");
return output;
}
輸出准確為
'This is a test'
我想修改我的第一種方法以正確運行並返回結果。
任何幫助表示贊賞。 謝謝 :)
您的模式不正確,它匹配開始的空白,您的輸入( greedy
)匹配直到最后一個空白,然后捕獲字符串末尾的最后一個空白。
您想要以下內容,在.*
加上?
以及非貪婪的比賽。
Pattern pattern = Pattern.compile("^\\s+(.*?)\\s+$");
正則表達式:
^ # the beginning of the string
\s+ # whitespace (\n, \r, \t, \f, and " ") (1 or more times)
( # group and capture to \1:
.*? # any character except \n (0 or more times)
) # end of \1
\s+ # whitespace (\n, \r, \t, \f, and " ") (1 or more times)
$ # before an optional \n, and the end of the string
觀看演示
編輯:如果您想將前導和尾隨空白捕獲到組中,只需將捕獲組()
放在它們周圍。
Pattern pattern = Pattern.compile("^(\\s+)(.*?)(\\s+)$");
1
包含前導空格 2
組包含您的匹配文本 3
包含尾隨空格 僅供參考,要替換前導/后綴空白,您可以在一行中實現。
input.replaceAll("^\\s+|\\s+$", "");
我意識到您正在使用Pattern
和Matcher
,但這是最簡單的方法:
private static String secondWay(String input) {
String pattern = "^\\s+|\\s+$"; // notice it's a string
return input.replaceAll(pattern, "");
}
正則表達式為^\\\\s+|\\\\s+$
,它匹配:
^
表示開始, \\\\s+
表示空格) |
表示或) $
表示行尾)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.