在句子中更易读的方式是不匹配否定词。

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

More readable way of not matching negated words in a sentence

问题

我正在尝试在句子中不匹配否定词,例如带有notnever等的形容词。目前我使用的是字符级别的否定。例如对于not,可以使用正则表达式^(?:[^n]+|n(?:$|[^o]|o(?:$|[^t]|\w)))。是否有更简单(更易读)的方法来处理一个或多个否定词(如notneveranynobody等)?以下是关于not否定的代码示例:

package main

import (
	"fmt"
	"regexp"
)

func main() {
	sentence := "he is not satisfied"
	re := regexp.MustCompile(`^(?:[^n]+|n(?:$|[^o]|o(?:$|[^t])))\ssatisfied`)
	fmt.Println(re.FindAllString(sentence, -1))
	sentence = "he is satisfied"
	fmt.Println(re.FindAllString(sentence, -1))
}

谢谢。

英文:

I am trying to not match negated word in a sentence such as adjective with not, never for example. Currently I used character level negation. Example for not ^(?:[^n]+|n(?:$|[^o]|o(?:$|[^t]|\w))). Is there an easy way (more readable) of doing this for one or many negation words (not, never, any, nobody, ......). Here is a code for not negation:

package main

import(
 "fmt"
 "regexp"
)

func main (){
	sentence:="he is not satisfied"
	re := regexp.MustCompile(`^(?:[^n]+|n(?:$|[^o]|o(?:$|[^t])))\ssatisfied`)
	fmt.Println(re.FindAllString(sentence, -1))
    sentence="he is satisfied"
	fmt.Println(re.FindAllString(sentence, -1))
}

Thanks

答案1

得分: 2

很遗憾,出于性能原因(尽管Go的正则表达式解析器本身并不特别高效),Go的正则表达式包不支持前瞻/后顾,因此没有很好的方法可以使用正则表达式来实现这个功能。

无论如何,正则表达式并不是很适合这种情况。它需要一个非常复杂的表达式来完成一个非常简单的匹配。如果我要实现类似的功能,我可能会将字符串按空格/标点符号分割,并进行自己的匹配。这样更容易处理,而且可能性能更好。

英文:

Unfortunately, for performance reasons (though the Go regexp parser is not particularly performant anyway), Go's regexp package does not support lookahead/lookbehind, so there is no great way to do this using regular expressions.

Regular expressions aren't a great fit for this anyway, though. It requires a very complex expression to do a very simple match. If I were implementing something similar, I would probably just split the string on spaces/punctuation and do my own matching. Easier to work with and likely better performance.

huangapple
  • 本文由 发表于 2017年7月20日 22:39:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/45217891.html
匿名

发表评论

匿名网友

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

确定