从字符串- regex中提取第一个单词

时间:2022-09-13 11:46:00

I have the following string:

我有以下字符串:


str1 = "cat-one,cat2,cat-3";
OR
str1 = "catone,cat-2,cat3";
OR
str1 = "catone";
OR
str1 = "cat-one";

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

这里的重点是单词可能/可能没有"-"s

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

使用regex:我如何提取第一个单词?

Appreciate any help on this.

感谢你的帮助。

Thanks, L

谢谢,我

3 个解决方案

#1


37  

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

很简单,只要在括号中包含允许的字符:

^([\w\-]+)

^((\ w \]+)

#2


1  

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

不使用regex的一种方法:假设第一个单词总是用逗号分隔,“您可以这样做:

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.

编辑:假定这是一个javascript问题,出于某种原因。

#3


0  

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()

#1


37  

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

很简单,只要在括号中包含允许的字符:

^([\w\-]+)

^((\ w \]+)

#2


1  

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

不使用regex的一种方法:假设第一个单词总是用逗号分隔,“您可以这样做:

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.

编辑:假定这是一个javascript问题,出于某种原因。

#3


0  

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()