如標題所述。例如:
注意:請仔細檢查這三個變數的值
String textA = 'this text contains many new line\n\n\n\nbut this ok, because there is a character after the new line';
String textB = 'I want remove all new Line because no character after new Line\n\n\n\n';
String textC = '\n\n\n\nAnd this still Ok, I dont want to remove all the new lines in front';
從該變數中,我們可以嘗試列印以查看結果
textA 將是
this text contains many new line
// new Line
// new Line
// new Line
but this ok, because there is a character after the new line
textB 將是
I want remove all new Line because no character after new Line
// new Line - I want delete this new Line
// new Line - I want delete this new Line
// new Line - I want delete this new Line
textC 將是
// new Line
// new Line
// new Line
And this still Ok, I dont want to remove all the new lines in front
你知道我們不能在文本欄位中輸入 \n(空格形式輸入你的鍵盤),當 \n 在最后一個字串中的位置時,\n 應該被洗掉。如何在飛鏢或顫振中解決這個問題?
uj5u.com熱心網友回復:
你可以試試這個正則運算式r'[\s\S]*\S'。
void main() {
final regex = RegExp(r'[\s\S]*\S');
String textA =
'this text contains many new line\n\n\n\nbut this ok, because there is a character after the new line';
String textB =
'I want remove all new Line because no character after new Line\n\n\n\n';
String textC =
'\n\n\n\n\nAnd this still Ok, I dont want to remove all the new lines in front';
print('-');
print(regex.firstMatch(textA)?.group(0));
print('-');
print(regex.firstMatch(textB)?.group(0));
print('-');
print(regex.firstMatch(textC)?.group(0));
print('-');
}

更新:您也可以嘗試str.trimRight(),我認為它很簡單并且作業方式相同。
final trimmed = '\nDart\n\n is fun\n\n'.trimRight();
print('-');
print(trimmed);
print('-');
// result
-
Dart
is fun
-
uj5u.com熱心網友回復:
我不確定您要使用哪種代碼來執行此操作,但方法是這樣的:
如果字串包含 '\n' 檢查字串是否以 '\n' 結尾,如果不是,則將 \n 替換為 ''。
uj5u.com熱心網友回復:
String 確實有一個函式 trim() 它將修剪文本前后的空間。
Text(
'I want remove all new Line because no character after new Line\n\n\n\n'.trim(),
)
uj5u.com熱心網友回復:
您可以使用此替換 \n 到 ''
var string = string.replaceAll('\n', '');
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/488083.html
下一篇:檢查物件?為空
