0

I am trying to find a substring in another string. I am using Regular expressions. The code is as below:

let occurrence = "Kingfisher:"
let string = "Swiss: SW123123\nKingfisher: KF994455\nQuantus: QS12343\nJetAir: FF7865667\nThai:  TH123442\nDelta: D123FGR\nAmerican: AME9879567\nGoAir: GO345682\nCathey: CATH020234\n        "
if let range = string.range(of: "\\b\(occurrence)\\b", options: .regularExpression) {
    print(range)
} else {
    print(occurrence, "not found.")
}

Why is my substring "Kingfisher:" not getting found.

Rohan Bhale
  • 1,323
  • 1
  • 11
  • 29
  • 1
    `:` is not a word char. `:\b` only matches the `:` that is followed with a letter/digit/`_`. Use `"(?<!\\w)\(occurrence)(?!\\w)"` or `"(?<!\\S)\(occurrence)(?!\\S)"`. – Wiktor Stribiżew Jun 30 '20 at 13:52
  • @WiktorStribiżew just to clarify my doubt are you saying in this case ":" which is a non word character is followed by " " which is also a non word character and hence the search fails? – Rohan Bhale Jun 30 '20 at 14:24
  • 1
    Since `:` is followed with a space, another non-word char, there is no match, right. `\b` meaining is context dependent. – Wiktor Stribiżew Jun 30 '20 at 14:26
  • @WiktorStribiżew in the "(?<!\\w)\(occurrence)(?!\\w)", the "(?!\\w)" is no use right because the assertion for that group happens after occurence has matched and that assertion wont affect the search. Is "(?<!\\w)\(occurrence)[\s\W]" more suitable for my case ?. I ask for more clarification because this lookahead and lookbehind is a bit complex for me to grasp. – Rohan Bhale Jul 02 '20 at 13:14
  • I guess `(?<!\w)occurrence(?!\S)` is a better bet if you need a right-hand whitespace boundary – Wiktor Stribiżew Jul 02 '20 at 13:17
  • True but then it will fail for cases where the characters after the occurence non word. – Rohan Bhale Jul 02 '20 at 13:18
  • (?<!\\w)(occurrence)[\s\W] is better fit here I guess. – Rohan Bhale Jul 02 '20 at 13:19
  • `\W` matches what `\s` matches. I told you need `(?<!\w)occurrence(?!\w)`. Use it. – Wiktor Stribiżew Jul 02 '20 at 13:26
  • As per this https://www.rexegg.com/regex-disambiguation.html#negative-lookahead But isnt the negative lookahead after occurence is matched not going to affect the search as it will just assert for the patterns after it and not before it? Or does the assert affect the result of matching before it as well – Rohan Bhale Jul 02 '20 at 13:29

0 Answers0