仅当超过一定大小时才从字符串中删除空格

时间:2016-09-30 13:30:53

标签: c#

我是这个字符串:

@Transactional
public Company updateCompany(Company company, final CompanyDto form) {
    company.getCompanyObjects().clear();
    company.getCompanyObjects().addAll(form.getCompanyObjects());
    for(CompanyObject obj : company.getCompanyObjects()){
       obj.setCompany(company);
    }
    return companyRepository.save(company);
}

此字符串最初采用以下格式:

QueryBuilder<Account, String> qb = accountDao.queryBuilder();
     Where where = qb.where();
     // the name field must be equal to "foo"
     where.eq(Account.NAME_FIELD_NAME, "foo");
     // and
     where.and();
     // the password field must be equal to "_secret"
     where.eq(Account.PASSWORD_FIELD_NAME, "_secret");
     PreparedQuery<Account, String> preparedQuery = qb.prepareQuery();

所以我使用Regex表达式删除了Corso Vittorio Emanuele II 9 20122 Milano

Corso Vittorio Emanuele II 9
      20122
      Milano

现在我试图以这种方式删除空格:

NewLine

但它没有按预期工作,&#39;因为我得到了这个结果:

var stringWithoutNewLine = Regex.Replace(text, "\t|\n|\r", string.Empty).Trim();

什么时候应该:

 return Regex.Replace(stringWithoutNewLine, @"\s+", string.Empty);

3 个答案:

答案 0 :(得分:2)

将正则表达式从@"\s+"更改为@"\s{2,}"。它将删除从2到(种类)无限数重复的空格。然后,正如Juharr所说,用空格替换:

Regex.Replace(yourString, @"\s{2,}", " ");

答案 1 :(得分:2)

你真的需要使用正则表达式吗?为什么不这样呢?

var splitString = text.Split(new char[0],StringSplitOptions.RemoveEmptyEntries);

var stringWithoutExtraSpaces = string.Join(" ",splitString);

答案 2 :(得分:1)

试试这个

2506:
144,43,7 | [Test]
144,45,7 | [Whatever]
146,43,7 | 

2418:
144,44,7 |
相关问题