dongzhuo6137 2019-04-29 07:55
浏览 141
已采纳

如何使用正则表达式分隔双引号字符串和非双引号字符串?

I'm trying to build a plugin which accepts parameters and each of the parameters can be a double quoted string or a non double quoted string.

Some examples of valid parameters :

  1. "random token"
  2. "random token" 34
  3. "randomtoken"

So I'm trying to write a parseParameters function which would return two values, one is the content inside double quoted string and the other is the non double quoted string.

I tried solving this problem with two regular expressions

  1. \"(.*?)\"\s*\d* - https://regex101.com/r/uB4sI9/145
  2. \"(.*?)\" - https://regex101.com/r/Pnh9Xd/1

Below is one version of the code I tried (which didn't work for some cases though) :

Variable parameters in the below code is going to be a list. Something like ["\"random, "token\"", "45"]

    paramString := strings.Join(parameters, " ")
    regex, _ := regexp.Compile(`\"(.*?)\"\s*\d*`)
    tempString := regex.FindString(paramString)
    if len(parameters) == 1 && tempString != "" {
        tempString = strings.TrimLeft(strings.TrimRight(tempString, `\"`), `\"`)
        return tempString, "", true
    }
    if paramString != tempString {
        return "", "", false
    }
    splitBySpace := strings.Split(tempString, " ")
    doubleQuoted := strings.TrimLeft(strings.TrimRight(tempString, `\"`), `\"`)
    nonDoubleQuoted := splitBySpace[len(splitBySpace)-1]
    return doubleQuoted, nonDoubleQuoted, true

Expected input and output:

Input : ["\"random", "token\""]

Output : "random token", "" (first value specifies the double quoted string while the other value specifies the non double quoted string)

Input : ["\"random", "token\"", "45"]

Output : ["\"random token\"", 45]

Note that double quotes are escaped in the input.

  • 写回答

1条回答 默认 最新

  • dsfs1233 2019-04-29 09:23
    关注

    You can use the regex.FindAllStringSubmatch.

    Following function would do the job, the function assumes the input to be a single string like "random token" 32

    func parse(str string) (string, string) {
        regex, _ := regexp.Compile(`("[^"]*")\s*(\S*)`)
        submatches := regex.FindAllStringSubmatch(str, -1)
        if len(submatches) == 0 {
            return "",""
        }
        return submatches[0][1], submatches[0][2]
    
    }
    

    You can find working link to a sample program here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#网络安全#的问题:求ensp的网络安全,不要步骤要完成版文件
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥20 使用Photon PUN2解决游戏得分同步的问题
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序