簡體   English   中英

正則表達式在特定單詞之前獲取所有單詞

[英]Regex get all words before a specific word

我想在一個特定單詞之前得到盡可能多的單詞,但這就是從所有行中獲取所有字符。

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

如果行與完整表達式不匹配,則無法匹配,為什么有些行仍然匹配?

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

多數民眾贊成在一個示例https://regexr.com/3to7l

謝謝

問題是\\s可以匹配換行符,並將整個輸入視為一個大匹配。

要修復您的正則表達式:

將第一部分[\\w\\s]+替換為.+ 這將給:

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

參見此處: RegexStorm工作示例

注意:這實際上會改變您的意圖,因為非單詞和非空格字符現在可以由.+匹配。 如果這是一個問題,則可能要使用^$\\A\\Z

參見此處以獲取更多信息,例如: https : //www.mikesdotnetting.com/article/46/c-regular-expressions-cheat-sheet

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

您可以使用此RegEx:

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

你可以在這里測試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM