正则表达式删除字符串中单词之间的空格

时间:2017-04-25 06:40:06

标签: sql regex hadoop hive

我正在使用Hive(Hadoop)编写类似SQL的语句。

我需要删除字段中的空格。例如,邮政编码可能是XX00 0XX,我想在0XX之前删除空格

到目前为止,我有这个正则表达式:

REGEXP_REPLACE(postcode, '[[:space:]]*', '')

但它似乎不起作用。有人可以建议吗?

3 个答案:

答案 0 :(得分:2)

只是做一个简单的(非正则表达式)替换会有什么问题吗?试试这个:

REPLACE(postcode, ' ', '')

如果您的version of Hive不支持REPLACE(),那么您可以使用:

REGEXP_REPLACE(postcode, '\\s+', '')

答案 1 :(得分:0)

你试过'[[:blank:]] *' 小心这也将捕捉标签。

答案 2 :(得分:0)

https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF

<强>翻译

// Init all values
var listItems = [String]()
var shopItems = [String]()
var cloudCheck = true
var onlineCheck = true

// Init the user defaults
let defaults = UserDefaults.standard

let privateDatabase = CKContainer.default().privateCloudDatabase
let recordZone = CKRecordZone(zoneName: "ShopListZone")
let predicate = NSPredicate(value: true)
var editedRecord: CKRecord!

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if let indexPath = tableView.indexPathForSelectedRow {
        tableView.deselectRow(at: indexPath, animated: true)
    }

    if (reachability?.isReachableViaWiFi)! || (reachability?.isReachableViaWWAN)! {

        if isICloudContainerAvailable() && defaults.bool(forKey: "changed") == false {
            getCloudData()
        }
        else if isICloudContainerAvailable() && defaults.bool(forKey: "changed") {
            loadOffline()
        }
        else {
            cloudCheck = false
        }
    } else {
        onlineCheck = false
        loadOffline()
    }
}

// Get the record from iCloud
func getCloudData() {

    // Connect to iCloud and fetch the data
    let query = CKQuery(recordType: "ShopListData", predicate: predicate)
    let operation = CKQueryOperation(query: query)
    var myItems = [String]()
    var allItems = [String]()

    operation.recordFetchedBlock = { record in
        myItems = record["ListItems"] as! [String]
        allItems = record["ShopItems"] as! [String]
    }

    operation.queryCompletionBlock = { [unowned self] (cursor, error) in
        DispatchQueue.main.async {
            if error == nil {
                self.listItems = myItems
                self.shopItems = allItems
                self.tableView.reloadData()
            } else {
                self.cloudCheck = false
                print("iCloud load error: \(String(describing: error?.localizedDescription))")
            }
        }
    }
    privateDatabase.add(operation)
    cloudCheck = true
}

// Upload and save the record to iCloud
@IBAction func uploadShopListData(_ sender: UIButton) {

    // Save the shop list in the user defaults
    defaults.set(listItems, forKey: "myItems")

    // Set bool if saving while offline
    if (reachability?.isReachableViaWiFi)! == false && (reachability?.isReachableViaWWAN)! == false {
        defaults.set(true, forKey: "changed")
    }

    // Save the record
    if cloudCheck && onlineCheck {
        defaults.set(false, forKey: "changed")
        saveRecord()
        // Show a short message if records were saved successfully
        self.myAlertView(title: "iCloud online", message: NSLocalizedString("Shop list was saved in iCloud.", comment: ""))

    } else {
        // Show a short message if iCloud isn't available
        myAlertView(title: "iCloud offline", message: NSLocalizedString("Shop list was saved on iPhone.", comment: ""))
        defaults.set(true, forKey: "changed")
    }
}

// Save the shop lists
func saveRecord() {

    // Connect to iCloud and start operation
    let query = CKQuery(recordType: "ShopListData", predicate: predicate)
    privateDatabase.perform(query, inZoneWith: recordZone.zoneID) {
        allRecords, error in
        if error != nil {
            // The query returned an error
            OperationQueue.main.addOperation {
                print("iCloud save error: \(String(describing: error?.localizedDescription))")

                // If there is now record yet, create a new one
                self.createRecord()
            }
        } else {
            // The query returned the records
            if (allRecords?.count)! > 0 {

                let newLists =  allRecords?.first
                newLists?["ListItems"] = self.listItems as CKRecordValue
                newLists?["ShopItems"] = self.shopItems as CKRecordValue

                self.privateDatabase.save(newLists!, completionHandler: { returnRecord, error in
                    if error != nil {
                        // Print an error message
                        OperationQueue.main.addOperation {
                            print("iCloud save error: \(String(describing: error?.localizedDescription))")
                        }
                    } else {
                        // Print a success message
                        OperationQueue.main.addOperation {
                            print("Shop list was saved successfully")
                        }
                    }
                })
            }
        }
    }
}

// Create a new record
func createRecord() {

    let myRecord = CKRecord(recordType: "ShopListData", zoneID: (self.recordZone.zoneID))
    let operation = CKModifyRecordsOperation(recordsToSave: [myRecord], recordIDsToDelete: nil)

    myRecord.setObject(self.listItems as CKRecordValue?, forKey: "ListItems")
    myRecord.setObject(self.shopItems as CKRecordValue?, forKey: "ShopItems")

    operation.modifyRecordsCompletionBlock = { records, recordIDs, error in
        if let error = error {
            print("iCloud create error: \(String(describing: error.localizedDescription))")
        } else {
            DispatchQueue.main.async {
                print("Records are saved successfully")
            }
            self.editedRecord = myRecord
        }
    }
    self.privateDatabase.add(operation)
    // Show a short message if icloud save was successfull
    self.myAlertView(title: "iCloud online", message: NSLocalizedString("Shop list was saved in iCloud.", comment: ""))
}

<强> REGEXP_REPLACE

select translate('XX00 0XX',' ','')

https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

<强>替换

select regexp_replace('XX00 0XX',' ','');
select regexp_replace('XX00 0XX','\\s','');
select regexp_replace('XX00 0XX','\\p{Blank}','');
select regexp_replace('XX00 0XX','\\p{Space}','');
select regexp_replace('XX00 0XX','\\p{javaWhitespace}','');

(从Hive 1.3.0和2.1.0开始)。