[英]Using regex to find a pattern which does not start with a certain String
I need to regex-match numbers in a certain pattern which works already, but only if there is not (+
right in front of it. 我需要以一种已经有效的特定模式对数字进行正则表达式匹配,但前提是没有(+
在它前面。
Example Strings I want to have a valid match within: 12
, 12.5
, 200/300
, 200/300/400%
, 1/2/3/4/5/6/7
例如字符串我想有内的有效匹配: 12
, 12.5
, 200/300
, 200/300/400%
1/2/3/4/5/6/7
Example Strings I want to have no valid match within: (+10% juice)
, (+4)
我希望在以下示例中没有有效匹配的示例字符串: (+10% juice)
, (+4)
I can already get all the valid matches with (\\d+[/%.]?)+
, but I need help to exclude the example Strings I want to have no valid match in (which means, only match if there is NOT the String (+
right in front of the mentioned pattern). 我已经可以使用(\\d+[/%.]?)+
/%。]?)+来获得所有有效的匹配项,但是我需要帮助来排除我不希望包含有效匹配项的示例字符串(这意味着仅在没有字符串的情况下才匹配(+
前面提到的模式)。
Can someone help me out? 有人可以帮我吗? I have already experimented with the !
我已经尝试过了!
(like ?!(\\(\\+)(\\d+[/%.]?)+
) but for some reason I can't it to work the way I need it. (例如?!(\\(\\+)(\\d+[/%.]?)+
),但由于某种原因,我无法使其按需要的方式工作。
(You can use http://gskinner.com/RegExr/ to test regex live) (您可以使用http://gskinner.com/RegExr/实时测试正则表达式)
EDIT: I did maybe use wrong words. 编辑:我可能使用了错误的单词。 I don't want to check if the searchstring does start with (+
but I want to make sure that there is no (+
right in front of my String. 我不想检查searchstring是否以(+
开始,但是我想确保在我的String前面没有(+
。
Try regexr with the following inputs: 使用以下输入尝试regexr:
Match: (\\d+[/%.]?)+
匹配: (\\d+[/%.]?)+
Check the checkbox for global
(to search for more than one match within the text) 选中global
复选框(以在文本中搜索多个匹配项)
Text: 文本:
this should find a match: 200/300/400
this shouldnt find any match at all: (+100%)
this should find a match: 40/50/60%
this should find a match: 175
Currently it will find a match in all 4 lines. 当前它将在所有4行中找到一个匹配项。 I want a regex that does no longer find a match in line 2. 我想要一个不再在第2行中找到匹配项的正则表达式。
The regex construct you are wanting is "Negative Lookbehind" - See http://www.regular-expressions.info/lookaround.html . 您想要的正则表达式构造是“负向后看”-请参见http://www.regular-expressions.info/lookaround.html 。 A negative lookbehind is defined like (?<!DONTMATCHME)
where DONTMATCHME is the expression you don't want to find just before the next bit of the expression. (?<!DONTMATCHME)
的否定定义为(?<!DONTMATCHME)
,其中DONTMATCHME是您不想在表达式的下一位之前找到的表达式。 Crutially, the lookbehind bit is not considered part of the match itself 至关重要的是,向后看位不视为比赛本身的一部分
Your expression should be: 您的表达应为:
(?<![+\d/\.])(\d+[/%.]?)+
Edit - changed negative lookbehind to any character that is not a + or another digit! 编辑-将负向后查找更改为非+或其他数字的任何字符! Edit #2 - moved the lookbehind outside the main capture brackets. 编辑#2-将后视移到了主要捕获括号之外。 Expanded the range of not acceptable characters before the match to include /
& .
扩大了比赛前不可接受的字符的范围,使其包含/
& .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.