Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression - starting and not ending with a pattern

Tags:

c#

regex

How do I put a regular expression to check if a string starts with certain pattern and is NOT ending with certain pattern.

Example:

Must StartsWith: "US.INR.USD.CONV"
Should not end with: ".VALUE"

Passes Regex: "US.INR.USD.CONV.ABC.DEF.FACTOR"
Fails Regex Check: "US.INR.USD.CONV.ABC.DEF.VALUE"

I am using C#.

like image 582
Cannon Avatar asked Dec 09 '22 05:12

Cannon


2 Answers

You can use this regex based on negative lookahead:

^US\.INR\.USD\.CONV(?!.*?\.VALUE$).*$

RegEx Demo

Explanation:

  • ^US\.INR\.USD\.CONV - Match US.INR.USD.CONV at start of input
  • (?!.*?\.VALUE$) - Negative lookahead to make sure line is not ending with .value
like image 55
anubhava Avatar answered Mar 07 '23 13:03

anubhava


^US\.INR\.USD\.CONV.*(?<!\.VALUE)$

Try this.See demo.

https://regex101.com/r/fA6wE2/26

Just use a negative lookbehind to make .VALUE is not before $ or end of string.

(?<!\.VALUE)$ ==>Makes sure regex engine looks behind and checks if `.VALUE` is not there when it reaches the end of string.
like image 30
vks Avatar answered Mar 07 '23 13:03

vks