htmlファイルからすべてのテーブル行を抽出しようとしています。 HTMLファイルを文字列に読み込んで解析します。その文字列を解析すると、テーブル行は決して見つけられませんが、ファイルと同じ内容の文字列から完全に同じ正規表現を使用すると、それは機能します。Regex - ファイルから作成された文字列からHTMLテーブル行を取得できませんが、コード内の文字列から動作します
問題を示す遊び場を付けました。私はなぜそれが私のハードコードされた文字列(私はファイルからコピーした)で動作しますが、ファイルを読み込んで作成された文字列からは出ません。
注:ファイルの内容が正確に私は、誰かがどのように質問
すべてのアイデアはにファイルを添付するために私を伝えることができるならば、全体の遊び場ファイルを添付しますcode.Iに使用した文字列と同じですか?ここで
import Foundation
extension String
{
func captureGroups(withRegex pattern: String, withStartPos startPos: inout Int) -> [String]
{
var results = [String]()
var regex: NSRegularExpression
// NSRegularExpression throws exception if error so I need to trap that
do {
regex = try NSRegularExpression(pattern: pattern, options: [])
}
catch {
return results
}
let matches = regex.matches(in: self, options: [],
range: NSRange(location:startPos, length: self.characters.count-startPos))
// Reset the string position to be the end od the currently matched expression
// This allows me to find the next thing in the string from where I left off
if let posFound = matches.first?.range.location
{
startPos = posFound + matches.first!.range.length // Start at end of last
}
guard let match = matches.first
else { return results }
let lastRangeIndex = match.numberOfRanges - 1
guard lastRangeIndex >= 1
else { return results }
for i in 1...lastRangeIndex {
let capturedGroupIndex = match.rangeAt(i)
let matchedString = (self as NSString).substring(with: capturedGroupIndex)
results.append(matchedString)
}
return results
}
} // extenstion String
var contents = ""
let path = Bundle.main.path(forResource: "testTR", ofType: "html")!
do {
contents = try String(contentsOfFile: path)
print("CONTENTS: \(contents)")
}
catch {
print("file not found")
}
var myStartPos: Int = 0
var foundMatch: [String]
foundMatch = contents.captureGroups(withRegex: "<tr>(.*)</tr>", withStartPos: &myStartPos)
if foundMatch.isEmpty{
print("Didnt find any rows ???")
}
myStartPos = 0
foundMatch = "<tr><td><strong>Total</strong></td><td><strong>1.2 mi</strong></td><td><strong>22:12</strong></td><td><strong>22:12</strong></td><td><strong>1:08/100m</strong></td><td><strong>1</strong></td><td><strong>2</strong></td><td><strong>4</strong></td></tr>".captureGroups(withRegex: "<tr>(.*)</tr>", withStartPos: &myStartPos)
私が使用していたファイルの内容は次のとおりです。
<tr>
<td><strong>Total</strong></td>
<td><strong>1.2 mi</strong></td>
<td><strong>22:12</strong></td>
<td><strong>22:12</strong></td>
<td><strong>1:08/100m</strong></td>
<td><strong>1</strong></td>
<td><strong>2</strong></td>
<td><strong>4</strong></td>
</tr>
使用している言語で質問してください。 – Bohemian