Regular Expressions

Can anybody help, please?
I just get my head round RegEx.
I am validating key fields and want the first character to be alphabetic, subsequent characters can be letters or numbers, no spaces or special characters. Key can be any length but advising it should be kept short.

I’ve tried

but all options seem to let anything through.

The first one should do the trick, my suspicion is your Xojo code is flawed. I would suggest posting that. Please enclose code in code tags (three backticks) or select your code and click the </> button in the post editor toolbar.

1 Like

The first option would require at least two characters, but otherwise should work. That leads me to believe the problem is in your code, not the expression.

If you will allow just one character, this will do it:


\A = beginning of document
\z = end of document
\d = digit

Xojo’s RegEx is case-INsensitive by default.

// The project key should start with a letter and consist only of letters and numbers
rg = new RegEx
rg.SearchPattern = “^[a-zA-Z][a-zA-Z0-9]+$”
rmatch = rg.Search(prjKey.Text)

This is the code. prjKey.text = ‘PRJ 1’
There should be no spaces but rmatch is null.

Right, the text does not match the pattern because it contains a space so match = nil. If you remove the space, it would match so match would contain a RegExMatch.

Okay. As I said in my first post, I can’t get my head round RegEx. I thought I was defining what the string should look like and it would tell me if it didn’t. So how do I negate the search pattern so it will tell me if prjKey is invalid?

You don’t need to. If there is no match (match = nil), it’s a bad string.

if rg.Search( prjKey.Text ) is nil then
  // It's not valid
end if

Ok, I’ll go with that.
Thanks for your help

As an aside, please note Tim’s comment above about tagging code blocks here. Doing so makes it easier to read and helps us help you.

1 Like

@John_Allen can you please mark the actual post that gives the answer (rather than your comment) as it will show up in the first post for future searchers. Also, can you please make your Titles more descriptive as, again when we search the forum in future and get a list of topics, we can see which ones might contain the question/answer we need, without having to drill down.

1 Like