正则表达式只打印每行的第一个字符串。

huangapple go评论95阅读模式
英文:

Regular expression only printing first string per line

问题

我正在尝试通过编写一个程序来获取更多的Go编程经验。该程序从一个.txt文件中获取输入,然后对每个字符串进行按字母顺序排序,并打印出每个字符串及其对应的行号。目前我遇到的问题是,当我将input.txt文件传递给程序时,它只打印出每行的第一个字符串。

package main

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

func main() {

    var i int = 0 //循环计数器

    var words1 string

    scanner := bufio.NewScanner(os.Stdin)

    //holdWords := make(map[string]int)
    //遍历txt文档并清理字符串行
    for scanner.Scan(){
        i=i+1

        words1=scanner.Text(); //获取行中的文本
        words1=strings.TrimSpace(words1) //去除前导和尾随空格

        reg, err:=  regexp.Compile("^[a-zA-Z]+") //用于查找字母/空格的正则表达式
        
        if err != nil{
            log.Fatal(err)
        }
        
        fmt.Println(reg.FindString(words1))//只是测试是否打印出正确的值
        
    }
}

以上是你提供的代码的翻译。

英文:

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
		
	}
}

答案1

得分: 1

如Simon所提到的,你应该使用FindAllString来查找所有匹配项。此外,你需要将正则表达式开头的^移除(^将模式锚定到字符串的开头)。为了提高效率,你还应该将regexp.Compile移到循环外面。

英文:

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.

答案2

得分: 0

根据这里的说明,FindAllString 返回正则表达式的所有连续匹配项的切片。而 FindString 则返回最左边的匹配项。

https://play.golang.org/p/Q_yfub0k80

英文:

https://play.golang.org/p/Q_yfub0k80

As mentioned here, FindAllString returns a slice of all successive matches of the regular expression. But, FindString returns the leftmost match.

huangapple
  • 本文由 发表于 2015年12月7日 07:40:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/34124246.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定