Home > Software engineering >  How to also match on Beginning and End of String in a CSV String
How to also match on Beginning and End of String in a CSV String

Time:07-23

I am simply needing to locate single digits of Seven, Eight or Nine that exist as a value in a CSV string. This string can also contain nothing or a single value, and so no commas if it is just a single value. I need to discover a RegEx Pattern that can match on just 7 or an 8 or a single 9. NOT 77... not 88 not 78 not 17 and not 97. Each match is looking for single value entries between each comma.

Currently, I have a Regular Expression that correctly locates the matches in between commas. However, it is failing to find those same matches when the value being searched is at the Beginning or the End of the string. Each time I try adding syntax to my RegEx to get it to find single 7s, 8s or 9s at the beginning or end, it then also starts finding non-valid entries within the String between commas such as 77 or 9Trunnion.

My Sample String: '7,8,9'.

My Pattern: (?<=,)[789](?=,)

Another Sample String: '15,7,98,0,null,Bad Data,9s,7,4,8'

Link to Demo: enter image description here

CodePudding user response:

Use look arounds:

(?<=^|,)[789](?=,|$)

See live demo.

  • Related