在swift中替换字符之间的字符串

时间:2017-02-27 14:12:29

标签: swift

我有很多字符串,如下:

'这是一张“桌子”。 “桌子”上有一个“苹果”。

我想用空格替换“table”,“apple”和“table”。有办法吗?

2 个答案:

答案 0 :(得分:3)

一个简单的正则表达式:

let sentence = "This is \"table\". There is an \"apple\" on the \"table\""

let pattern = "\"[^\"]+\"" //everything between " and "
let replacement = "____"
let newSentence = sentence.replacingOccurrences(
    of: pattern,
    with: replacement,
    options: .regularExpression
)

print(newSentence) // This is ____. There is an ____ on the ____

如果你想保持相同数量的字符,那么你可以迭代匹配:

let sentence = "This is table. There is \"an\" apple on \"the\" table."    
let regularExpression = try! NSRegularExpression(pattern: "\"[^\"]+\"", options: [])

let matches = regularExpression.matches(
    in: sentence,
    options: [],
    range: NSMakeRange(0, sentence.characters.count)
)

var newSentence = sentence

for match in matches {
    let replacement = Array(repeating: "_", count: match.range.length - 2).joined()
    newSentence = (newSentence as NSString).replacingCharacters(in: match.range, with: "\"" + replacement + "\"")
}

print(newSentence) // This is table. There is "__" apple on "___" table.

答案 1 :(得分:0)

我写了一个扩展来做到这一点:

let arr1 = [
{
  "_id": "PU2-TEXT BOOK",
  "dispatchcount": 2,
  "totalDispatchValue": 5810,
  "totalDiscountValue": 150
},
{
  "_id": "PU2-Mathematics Part - 1 Text Book",
  "dispatchcount": 1,
  "totalDispatchValue": 4131,
  "totalDiscountValue": 150
},
{
  "_id": "Boys White & Blue Striped Half Shirt",
  "dispatchcount": 1,
  "totalDispatchValue": 4131,
  "totalDiscountValue": 150
}
  ]

  let arr2 = [
{
  "_id": "PU2-TEXT BOOK",
  "pendingcount": 2,
  "totalPendingValue": 14157,
  "totalPendingDiscountValue": 1518
},
{
  "_id": "PU2-Accountancy Part - 2 Text Book",
  "pendingcount": 1,
  "totalPendingValue": 9002,
  "totalPendingDiscountValue": 834
}
  ]

let  restProperties = { dispatchcount: 0, totalDispatchValue: 0, totalDiscountValue: 0, pendingcount: 0, totalPendingValue: 0, totalPendingDiscountValue: 0 };
let uniqueArr2 = new Map(arr2.map((s)=>([s._id, s])));
arr1 = arr1.map(({_id, ...rest}) => ({_id, ...restProperties, ...rest, ...uniqueArr2.get(_id) }));
const other = arr2.filter(f => !arr1.some(s=> s._id == f._id)).map(s => ({...restProperties, ...s  }));
console.log([...arr1, ...other]);