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 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类