-1

I'd like to create a regex for a passcode where users signify their number is a passcode with words and a double colon before the code or a hash after the word. So I'd like both of the following to be accepted:

code: 1234567
123567#

However as '#' and 'code: ' are at opposite ends of the pattern my current way of doing this is repeating my entire regex twice as follows.

(?:(?:code|pc|#|participant)[:>]?#?(\\d{7,8}(?!\\d)))|((?<!\\d)\\d{7,8})#

I'm essentially saying prefix words + passcode OR passcode + #

When I'd like to say prefix words OR a hash at the end + passcode. Is the latter possible?

Declan McKenna
  • 4,321
  • 6
  • 54
  • 72

1 Answers1

0

You could just use string manipulation instead of regex with a little extension:

extension String {
    func beginsWith (str: String) -> Bool {
        if let range = self.rangeOfString(str) {
            return range.startIndex == self.startIndex
        }
        return false
    }

    func endsWith (str: String) -> Bool {
        if let range = self.rangeOfString(str, options:NSStringCompareOptions.BackwardsSearch) {
            return range.endIndex == self.endIndex
        }
        return false
    }
}

And then:

if(codeString.beginsWith("code:") || codeString.endsWith("#")
     //Something
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
  • Which out of the string manipulation and a regular expression is more efficient and how will factors such as increasing the number of words we look for affect the efficiency? – Declan McKenna Jan 15 '16 at 16:49
  • @Deco regex is great for complex pattern, which is not what you asked here. Plus: Idk about swift but in many languages string manipulation is way faster than regex as your seed grow – Thomas Ayoub Jan 15 '16 at 16:52
  • I'll do some testing on them both. I've heard string manipulation is faster in most cases but the fact the regex has all of the values at once makes me think it would just need one run through the string checking for the first letter of each string within the negative look behind. String manipulation has to go through the string N number of times where N is the number of values I feed in to the beginsWith function. – Declan McKenna Jan 15 '16 at 17:00