dsgffz2579 2019-05-13 00:10
浏览 105
已采纳

查找格式错误的带引号的字符串的正则表达式

I am trying to build an regular expression for sub string which have a starting quote but didn't have ending quote. Below is an sample string

"The fish was 2 long. I said: Give me that fish!.
The fish was 2" long. I said: Give me that fish!.
"The fish was 2 long. I said: Give me that fish!."
The fish "was 2 long". I said: "Give me that fish!.

So the valid output for the expression would be

String 1 - The fish was 2 long. I said: Give me that fish!
String 2 -  long. I said: Give me that fish!.
String 3 - No output
String 4 - Give me that fish!.

Any thoughts how I can build the regular expression.

  • 写回答

1条回答 默认 最新

  • doucigua0449 2019-05-13 01:05
    关注

    Doing all with regex can be done.. will take some more time to perfect the solution. But using some strings function will make it bit easy for you.

    Hope this helps!!

    package main
    
    import (
    "fmt"
    "regexp"
    "strings"
    )
    
    func main() {
    str := `
        "The fish was 2 long. I said: Give me that fish!.
    The fish was 2" long. I said: Give me that fish!.
    "The fish was 2 long. I said: Give me that fish!."
    ""sdfsdf
    `
    splitStr := strings.Split(str, "
    ")
    re := regexp.MustCompile(`"{1}[A-Za-z0-9 .:!]+"{0}[A-Za-z0-9 .:!]+$`)
    for _,v := range splitStr {
        if len(strings.Trim(v, " ")) >= 0{
        // some extra check
        if strings.Count(v, "\"") % 2 == 1 {
            fmt.Println( re.FindString(v))
        }
    
        } 
    }
    

    }

    Code sample available here: https://play.golang.org/p/LYte6FRocv3

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

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题