开发者

extract the first word from a string - regex

I have the following string:


str1 = "cat-one,cat2,cat-3";
OR
str1 = "c开发者_高级运维atone,cat-2,cat3";
OR
str1 = "catone";
OR
str1 = "cat-one";

The point here is words may/may not have "-"s in it

Using regex: How could I extract the 1st word?

Appreciate any help on this.

Thanks, L


It's pretty easy, just include allowed characters in brackets:

^([\w\-]+)


An approach not using a regex: assuming the first word is delimited always by a comma "," you can do this:

var str1 = "cat-one";
var i = str1.indexOf(",");
var firstTerm = i == -1 ? str1 : str1.substring(0, i);

Edit: Assumed this was a javascript question, for some reason.


If someone, one day would like to do it in Swift here you go with an extension :

extension String {

    func firstWord() -> String? {
        var error : NSError?
        let internalExpression = NSRegularExpression(pattern: "^[a-zA-Z0-9]*", options: .CaseInsensitive, error: &error)!
        let matches = internalExpression.matchesInString(self, options: nil, range:NSMakeRange(0, countElements(self)))
        if (matches.count > 0) {
            let range = (matches[0] as NSTextCheckingResult).range
            return (self as NSString).substringWithRange(range)
        }
        return nil
    }
}

To use it just write:

myString.firstWord()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜