-1

I searched everywhere but it does not correspond to my request. How to check if a string matches with a regex ? I don't want to know if my string contains caracters or which they are but I want to do a function which returns true or false : does this string "abcdefgh" matches with "[a-z]".

I can do it in PHP, JS but apparently in Swift all people want only to know which caracters matche. ^^

Regards,

Tchoupinax
  • 235
  • 3
  • 12
  • `print("abcdefgh".range(of: "[a-z]", options: .regularExpression) != nil)` – Wiktor Stribiżew Aug 01 '17 at 19:49
  • `print("abcdef2gh".range(of: "[a-z]", options: .regularExpression) != nil)` returns true although it should not – Tchoupinax Aug 01 '17 at 20:12
  • Why shouldn't? There is a lowercase ASCII char in that string. It is a *partial match*. Do you need a full string match? How do you do that in PHP and JS then? :) Neither PHP nor JS have a full string regex matching method. BTW, Swift has one. – Wiktor Stribiżew Aug 01 '17 at 20:13
  • And this ? ^^ `console.log(/^([a-z]*)$/.test('abcdefgh')) // true | console.log(/^([a-z]*)$/.test('abcd2efgh')) // false`. Test yourself. It is what i would like to do in Swift. How do you do ? [[Source : https://stackoverflow.com/questions/6603015/check-whether-a-string-matches-a-regex ]] – Tchoupinax Aug 01 '17 at 20:25
  • You are using anchors and quantifiers. Use them with my solution, you will get the same behavior. `print("abcdefgh".range(of: "^[a-z]*$", options: .regularExpression) != nil)`. `RegExp#test` only searches for partial matches, it is the `^` and `$` that make the JS regex engine ensure a full string match. Anyway, your question is a dupe. – Wiktor Stribiżew Aug 01 '17 at 20:26
  • All right ! You were right. The function was the good one, i did not use the good regex. Thanks Man ! – Tchoupinax Aug 01 '17 at 20:30

1 Answers1

2

You shouldn't blankly import ideas from one language to another:

let regex = try! NSRegularExpression(pattern: "[a-z]", options: [])
let str = "abcdefgh"

let isMatch = regex.firstMatch(in: "abcdefgh", options: [], range: NSMakeRange(0, str.utf16.count)) != nil
Code Different
  • 90,614
  • 16
  • 144
  • 163