duanmu6231 2016-06-23 02:01
浏览 286
已采纳

正则表达式-捕获空格分隔的单词

I have a string:

2001 970451 4 l 97 0451 iver b y c 3 0 1 8 4 1 4 hundred 2001 970451 nama 4 l 97 0451 iver hundred blah

I need an appropriate regular expression to capture series of characters and spaces such as b y c 3 0 1 8 4 1 4?

I have tried:

(\b[a-z0-9]{1}\s{1})+ - I get l

EDIT:

To further explain what I need, I need to be able to capture similar series of text where a single alphanum character is continuously/repeatedly followed by single space character to a point where this is no longer true.

  • 写回答

3条回答 默认 最新

  • dongyan8929 2016-06-23 12:17
    关注

    Is regexp a hard requirement?

    It would be far simpler for you, in the long term, to just use something like strings.Fields and filter the resulting array by length (you can apply any other requirements too).

    Example:
    (Give it a try on the playground! https://play.golang.org/p/Ue2wO5d-Te)

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func CaptureGroups(input string) (output [][]string) {
        fields := strings.Fields(input)
    
        var group []string
        for _, field := range fields {
            if len(field) == 1 {
                group = append(group, field)
            } else {
                if len(group) > 0 {
                    output = append(output, group)
                    group = make([]string, 0)
                }
            }
        }
    
        return
    }
    
    func main() {
        input := "2001 970451 4 l 97 0451 iver b y c 3 0 1 8 4 1 4 hundred 2001 970451 nama  4 l 97 0451 iver hundred blah"
        output := CaptureGroups(input)
    
        fmt.Printf("Groups: %q", output)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的