douxianxing5712 2015-12-06 23:40
浏览 343

正则表达式每行仅打印第一个字符串

I'm trying to get more experience with Go by writing a program that takes input from a .txt file, then sorts each string alphabetically and prints each one out with it's corresponding line number. Right now I'm having a problem where my program is only printing out the first string per line when I pass it my input.txt file

package main

import "fmt"
import "regexp"
import "bufio"
import "log"
import "os"
import "strings"

func main() {

    var i int = 0 //counter for loop

    var words1 string

    scanner := bufio.NewScanner(os.Stdin)

    //holdWords := make(map[string]int)
    //Loop through the txt doc and cleanup the lines of strings
    for scanner.Scan(){
        i=i+1

        words1=scanner.Text(); //get the text from line
        words1=strings.TrimSpace(words1) //trim the trailing and leading whitespace

        reg, err:=  regexp.Compile("^[a-zA-Z]+") //regex to look for letters/spaces

        if err != nil{
            log.Fatal(err)
        }

        fmt.Println(reg.FindString(words1))//just testing to see if it prints correct values

    }
}
  • 写回答

2条回答 默认 最新

  • douyan3478 2016-01-24 22:58
    关注

    As Simon mentioned, you should be using FindAllString to find all matches. Also, you need to remove the ^ from the beginning of the RE (^ anchors the pattern to the beginning of the string). You should also move the regexp.Compile outside the loop for efficiency.

    评论

报告相同问题?

悬赏问题

  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答