假設我有這個文本檔案(已經加載到一個名為“strContent”的字串中)
Algebra 0 arujabura
Algebra 0 daishu
Kangaroo 0 daishu
Geometry 0 jiometori
Geometry 0 jihe
Physics 0 fijikusu
Physics 0 wuli
正則運算式 A:(^.*Algebra.*\b(arujabura)\b.*$
有一個私人原因使用并且只使用全字分支\b()\b到第二列。)
Regex B 是一種替換模式,用于在上述 Regex A 匹配的行內\b(arujabura)\b執行搜索:查找并將其替換為アルジャブラ.
但是,我無法使用以下縮短的示例在此處匹配任何內容:
#!/usr/bin/env swift
import Foundation
extension String {
/* https://stackoverflow.com/a/66189289/4162914 */
func match(_ pattern: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options(rawValue: 0))
let nsstr = self as NSString
let all = NSRange(location: 0, length: nsstr.length)
var matches : [String] = [String]()
regex.enumerateMatches(in: self, options: [], range: all) {
(result : NSTextCheckingResult?, _, _) in
if let r = result {
let result = nsstr.substring(with: r.range) as String
matches.append(result)
}
}
return matches
} catch {
return [String]()
}
}
}
func filterTone_Romaji(inputString: String) -> [String] {
var arrResult = inputString.match("^.*Algebra.*\\b(arujabura)\\b.*$")
arrResult.append(contentsOf: inputString.match("^.*Geometry.*\\b(jiometori)\\b.*$"))
arrResult.append(contentsOf: inputString.match("^.*Physics.*\\b(Fijikusu)\\b.*$"))
return arrResult
}
let str_Test_File = "Algebra 0 arujabura\nAlgebra 0 daishu\nKangaroo 0 daishu\nGeometry 0 jiometori\nGeometry 0 jihe\nPhysics 0 fijikusu\nPhysics 0 wuli"
// Trying to find the matched result
var arrConvResultTest : [[String]] = [[]]
arrConvResultTest.append(["@# phrases-test-pragma-header.txt"])
var arrConv_Test_File = filterTone_Romaji(inputString: str_Test_File)
// Print Out the matched result
var varLineData = ""
for lineData in arrConvResultTest {
varLineData = lineData.joined()
print(varLineData)
}
接下來我應該怎么做才能確保它匹配?
PS:關于替換,我假設我可以使用以下方法:
extension String {
/* https://stackoverflow.com/a/40993403/4162914 */
mutating func regReplace(pattern: String, replaceWith: String = "") {
do {
let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let range = NSRange(location: 0, length: count)
self = regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replaceWith)
} catch { return }
}
}
更新
我嘗試了上面答案執行緒中給出的解決方案之一。但是,看起來范圍不起作用。否則,袋鼠的價值不應該受到影響:
#!/usr/bin/env swift
import Foundation
extension String {
mutating func inlineRep(regLineMatch: String, replaceOf: String, replaceWith: String) {
let rangeWithinLine = self.range(of: regLineMatch, options: .regularExpression)
let result = self.replacingOccurrences(of: replaceOf,
with: replaceWith,
options: .regularExpression,
range: rangeWithinLine)
self = result
}
}
var strClusterTest = "Algebra 0 arujabura\nAlgebra 0 daishu\nKangaroo 0 daishu\nGeometry 0 jiometori\nGeometry 0 jihe\nPhysics 0 fijikusu\nPhysics 0 wuli"
strClusterTest.inlineRep(regLineMatch: #"\n^.*Algebra.*\b(daishu)\b.*$\n"#, replaceOf: #"\b(daishu)\b"#, replaceWith: "代數")
print(strClusterTest)
我添加了一個回圈容器,試圖將編輯范圍限制為當前行,但正則運算式范圍仍然無法正常作業:
#!/usr/bin/env swift
import Foundation
extension String {
mutating func inlineRep(regLineMatch: String, replaceOf: String, replaceWith: String) {
let rangeWithinLine = self.range(of: regLineMatch, options: .regularExpression)
let result = self.replacingOccurrences(of: replaceOf,
with: replaceWith,
options: .regularExpression,
range: rangeWithinLine)
self = result
}
}
var strClusterTest = "Algebra 0 arujabura\nAlgebra 0 daishu\nKangaroo 0 daishu\nGeometry 0 jiometori\nGeometry 0 jihe\nPhysics 0 fijikusu\nPhysics 0 wuli"
var arrClusterTest = strClusterTest.components(separatedBy: "\n")
var strClusterOutputTest = ""
for line in arrClusterTest {
var currentLine = line
currentLine.inlineRep(regLineMatch: #"^.*Algebra[^\n]\b(daishu)\b.*$"#, replaceOf: #"\b(daishu)\b"#, replaceWith: "代數")
strClusterOutputTest = currentLine
strClusterOutputTest = "\n"
}
print(strClusterOutputTest)
uj5u.com熱心網友回復:
您可以使用range(of:options)查找正則運算式
let range = str_Test_File.range(of: regex, options: .regularExpression)
然后replacingOccurrences(of:with:options:range)執行替換
replacingOccurrences(of: #"\barujabura\b"#, with: replacement, options: .regularExpression, range: range)
所以完整的代碼是
let str_Test_File = "Algebra 0 arujabura\nAlgebra 0 daishu\nGeometry 0 jiometori\nGeometry 0 jihe\nPhysics 0 fijikusu\nPhysics 0 wuli"
let regex = #"^.*Algebra.*\b(arujabura)\b.*$"#
let replacement = "アルジャブラ"
let range = str_Test_File.range(of: regex, options: .regularExpression)
let result = str_Test_File.replacingOccurrences(of: #"\barujabura\b"#,
with: replacement,
options: .regularExpression,
range: range)
我不太確定為什么你需要把它變成一個兩步的程序,所以作為替代方案,也許你可以直接做
let result = str_Test_File.replacingOccurrences(of: #"\barujabura\b"#,
with: replacement,
options: .regularExpression)
至少對于給定的測驗字串,兩種解決方案的最終結果是相同的。
更新
如果您想創建一個回圈來遍歷并單獨替換所有匹配項,我會使用這樣的while回圈
var searchRange = strClusterTest.startIndex..<strClusterTest.endIndex
while let range = strClusterTest.range(of: regLineMatch,
options: .regularExpression,
range: searchRange) {
strClusterTest = strClusterTest.replacingOccurrences(of: replaceOf,
with: replaceWith,
options: .regularExpression,
range: range)
searchRange = range.upperBound..<strClusterTest.endIndex
}
該searchRange變數用于僅搜索最后一次匹配之后range(of:)的字串部分,回傳 nil時將退出回圈。我也相信搜索正則運算式可以更改為
let regLineMatch = #"\n?.*Algebra.*\b(daishu)\b.*\n"#
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/429155.html
標籤:迅速
