1

I would like to check if a given String is in a amount format. A few examples for a better understanding:

Should return true:

2x

31x

3x abcd

Should return false:

2x3

3xabc

asdf3x

So in general: it has to start with a number (0-9), can be more digits. Right after the number a "x"/"X" should follow and after the "x"/"X" should be the end or a white space.

I am struggling to get this done.. This is what I tried:

func isAmountFormat() -> Bool {
    return self.matches("[0-9]+[X,x]")
}

Can anyone help me out here?

Chris
  • 1,828
  • 6
  • 40
  • 108

1 Answers1

1

You may use

"(?i)\\b[1-9][0-9]*x\\b"

See the regex demo. Details:

  • (?i) - case insensitive flag (in case you cannot pass the .caseInsensitive in your current regex matching method)
  • \b - a word boundary
  • [1-9] - a non-zero digit
  • [0-9]* - any zero or more digits
  • x - an X or x
  • \b - a word boundary.

See a Swift snippet:

let test = "3x abcd"
if test.range(of: "\\b[1-9][0-9]*x\\b", options: [.regularExpression, .caseInsensitive]) != nil {
    print("Matched")
} else {
   print("No match")
}

Note that if the match should occur at the start of the string, you may compile the regex object with the .anchored option, or replace the first \\b with ^.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563