简体   繁体   English

正则表达式在特定单词之前获取所有单词

[英]Regex get all words before a specific word

I want to get many words as possible before a specific word, but this is getting all characters from all lines. 我想在一个特定单词之前得到尽可能多的单词,但这就是从所有行中获取所有字符。

([\\w\\s]+)( Subtract| Add) is (\\d+) credits

If the the line don't match with full expression it's can't be match, why some lines match anyway? 如果行与完整表达式不匹配,则无法匹配,为什么有些行仍然匹配?

This line cannot match This line cannot match too No way to match Why is matching this line Apple Banana Orange Add is 34 credits Watermelon Strawberry Subtract is 20 credits Sugar Add is 8 credits

thats a sample https://regexr.com/3to7l 多数民众赞成在一个示例https://regexr.com/3to7l

Thanks 谢谢

the problem is that \\s can match the newlines, and treat the whole of your input as one big match. 问题是\\s可以匹配换行符,并将整个输入视为一个大匹配。

To fix your regex : 要修复您的正则表达式:

Replace the first part [\\w\\s]+ by .+ . 将第一部分[\\w\\s]+替换为.+ This will give : 这将给:

(.+)( Subtract| Add) is (\d+) credits

see here : RegexStorm working example 参见此处: RegexStorm工作示例

Note : this actually changes a bit your intent, because non-word and non-space characters can now be matched by .+ . 注意:这实际上会改变您的意图,因为非单词和非空格字符现在可以由.+匹配。 If this is a problem, you might want to use ^ , $ , \\A or \\Z . 如果这是一个问题,则可能要使用^$\\A\\Z

See here for more info, for instance : https://www.mikesdotnetting.com/article/46/c-regular-expressions-cheat-sheet 参见此处以获取更多信息,例如: https : //www.mikesdotnetting.com/article/46/c-regular-expressions-cheat-sheet

or https://download.microsoft.com/download/D/2/4/D240EBF6-A9BA-4E4F-A63F-AEB6DA0B921C/Regular%20expressions%20quick%20reference.pdf https://download.microsoft.com/download/D/2/4/D240EBF6-A9BA-4E4F-A63F-AEB6DA0B921C/Regular%20expressions%20quick%20reference.pdf

You can use this RegEx: 您可以使用此RegEx:

.*(?: Subtract| Add) is \d+ credits

and you can test it here 你可以在这里测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM