从子字符串中获取字符串

时间:2018-04-30 10:05:35

标签: ios swift string

我有以下字符串"@[Hema](hema_ramburuth), @[Ilesh P](ilesh.panchal), @[Lewis Murphy](lewis) how are you?"。我希望像"Hema, Ilesh P, Lewis Murphy how are you?一样显示此屏幕“我还要确定点击事件的屏幕。

我已使用ActiveLabel个回复进行点击。

2 个答案:

答案 0 :(得分:2)

嘿,我遇到了类似的要求。所以这就是我的处理方式。

我为String

创建了一个扩展程序
extension String {
    /// Returns range of text in the string
    func getRange(OfText text: String) -> NSRange {
        let nsRepresentation = self as NSString
        return nsRepresentation.range(of: text)
    }
} 

在视图控制器中,

var tapPrivacyGesture = UITapGestureRecognizer()
@IBOutlet weak var yourLabel: UILabel!
var displayText = String()

func matchesForRegexInText(regex: String, text: String, firstBracket: String, lastBracket: String) -> [String] {
    do {
        let regex = try NSRegularExpression(pattern: regex, options: [])
        let nsString = text as NSString
        let results = regex.matches(
            in: text,
            options: [],
            range: NSRange(location: 0, length: nsString.length))
        return results.map { nsString.substring(with: $0.range) }.map { $0.replacingOccurrences(of: firstBracket, with: "") }.map { $0.replacingOccurrences(of: lastBracket, with: "") }
    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

var givenString = "@[Hema](hema_ramburuth), @[Ilesh P](ilesh.panchal), @[Lewis Murphy](lewis) how are you?"
let nameStrings = matchesForRegexInText(regex: "\\[(.*?)\\]", text: givenString, firstBracket: "[", lastBracket: "]")
let removeForUIStrings = matchesForRegexInText(regex: "\\((.*?)\\)", text: givenString, firstBracket: "(", lastBracket: ")")

removeForUIStrings.forEach {
    givenString = givenString.replacingOccurrences(of: "(\($0))", with: "")
}
nameStrings.forEach {
    givenString = givenString.replacingOccurrences(of: "[\($0)]", with: $0)
}
givenString = givenString.replacingOccurrences(of: "@", with: "")
print(givenString)
displayText = givenString

tapPrivacyGesture.addTarget(self, action: #selector(self.handlePolicyTap(tap:)))
yourLabel.addGestureRecognizer(tapPrivacyGesture)
yourLabel.isUserInteractionEnabled = true


func handlePolicyTap(tap: UITapGestureRecognizer) {
    let storage = NSTextStorage(attributedString: yourLabel.attributedText ?? NSAttributedString())
    let layoutManager = NSLayoutManager()
    storage.addLayoutManager(layoutManager)

    let textContainer = NSTextContainer(size: CGSize(width: yourLabel.frame.size.width, height: yourLabel.frame.size.height+100))
    textContainer.lineFragmentPadding = 0.0
    textContainer.lineBreakMode = (yourLabel.lineBreakMode)
    textContainer.maximumNumberOfLines = yourLabel.numberOfLines
    layoutManager.addTextContainer(textContainer)

    let location: CGPoint = tap.location(in: yourLabel)
    let characterIndex: Int = layoutManager.characterIndex(for: location, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)

    guard
        characterIndex < storage.length,
        let question = currentQuestion else {
            return
    }
    nameStrings.forEach {
        let range = displayText.getRange(OfText: $0)
        if range.contains(characterIndex) {
            /// Perform actions on click of this string
        }
    }
}

答案 1 :(得分:0)

从您的问题开始,只需在下面进行硬编码解析。

    let fullString = "@[Hema](hema_ramburuth), @[Ilesh P](ilesh.panchal), @[Lewis Murphy](lewis) how are you?"
    let allarray = fullString.split(separator: ",")
    let messageArray = allarray.last
    let message = messageArray?.split(separator: ")")
    let correctMessage = message?.last

    var allNames : String  = ""
    for namesString in allarray {
        if allNames.count > 0 {
            allNames += ", "
        }
        let name = String(namesString)
        allNames += name.slice(from: "@[", to: "]") ?? ""
    }
    if allNames.count > 0 {
        allNames += correctMessage ?? ""
    }
    print("Name and Message --- > \(allNames)")

使用String extension

切片字符串
extension String {

    func slice(from: String, to: String) -> String? {

        return (range(of: from)?.upperBound).flatMap { substringFrom in
            (range(of: to, range: substringFrom..<endIndex)?.lowerBound).map { substringTo in
                substring(with: substringFrom..<substringTo)
            }
        }
    }
}

我打印输出如下:

  

姓名和留言---&gt; Hema,Ilesh P,Lewis Murphy你好吗?