Pradeep
Pradeep

Reputation: 99

Regex for comparing Strings with spaces

Im trying to compare is a string is present among a list of Strings using regex.

I tried using the following...

(?!MyDisk1$|MyDisk2$)

But this isnt working... for the scenarios like

(?!My disk1$|My Disk2$)

Can you suggest a better approach to deal with such situations..

I get the list of strings from an sql query... So I am not sure where the spaces are present. The list of Strings vary like My Disk1, MyDisk2, My_Disk3, ABCD123, XYZ_123, MNP 123 etc.... or any other String with [a-zA-Z0-9_ ]

Upvotes: 0

Views: 97

Answers (3)

Shikhar Subedi
Shikhar Subedi

Reputation: 616

You can do this:

/(?[^\s_-]+(\s|_|-)?[^\s_-]*?$)/i

'?' quantifier means 0 or 1 of the preceding pattern. /i is for case insensitive. The separator can be space or underscore or dash.I have replace My and disk with a string of length 1 or more which does not contain space ,underscore or dash.. Now it wil match "Shikhar Subedi" "dprpradeep" or "MyDisk 54".

The + quantifier means 1 or more. ^ means not. * means 0 or more. So the string after the space is optional.

Upvotes: 0

p.s.w.g
p.s.w.g

Reputation: 149020

You can make the spaces optional using a zero-or-one quantifier (?):

(?!My ?disk1$|My ?Disk2$)

This assertion will reject substrings like MyDisk2 or My Disk2. Or to handle potentially many spaces, use a zero-or-more quantifier (*):

(?!My *disk1$|My *Disk2$)

Note that if you're running this in an engine which ignores whitespace in the pattern you may need to use a character class, like this:

(?!My[ ]*disk1$|My[ ]*Disk2$)

Or to handle spaces or underscores:

(?!My[ _]*disk1$|My[ _]*Disk2$)

Unfortunately if the spaces can be anywhere in the string, (but you still care about matching the other letters in order), you'd have to do something like this:

(?! *M *y *d *i *s *k *1$| *M *y *D *i *s *k *2$)

Or to handle spaces or underscores:

(?![ _]*M[ _]*y[ _]*d[ _]*i[ _]*s[ _]*k[ _]*1$|[ _]*M[ _]*y[ _]*D[ _]*i[ _]*s[ _]*k[ _]*2$)

But to be honest, at that point, you may be better off preprocessing your data before you try to use your regex with it.

Upvotes: 1

dirtydexter
dirtydexter

Reputation: 1073

use this Regex upending i at the end that will mean that your regex is case-insensitive

/my\s?disk[12]\$/i

this will match all possible scenarios.

Upvotes: 0

Related Questions