0

I am trying to get all regexp matching the following:

/* anything could be in here */

I have not used regular expressions in swift before. I would imagine it should look something like

var regexpPattern = "\/\*.*\*\/"
var regexp = try NSRegularExpression(pattern: regexpPattern, options: []);
var regexpMatches = regexp.matches(in: THESTRING, options: .anchored, range: NSRange(location: 0, length: THESTRING.characters.count))

However i get the error "invalid escape sequence in literal". I am a little confused as how to use this since i need to provide the pattern in a String. Other languages i used have regexp delimiters, is there such a thing here?

Thanks for taking the time.

EDIT: Solved by Wiktor Stribiżew. Needed to add an extra backslash to escape the backslash.I had originally done that however the real reason i was not receiving any results was because i was using .anchored in the options.

Return-1
  • 1,953
  • 1
  • 12
  • 44
  • Sorry, what is the pattern in the P.S. part? `\ \ / \ \ *.* \ \ * \ \ /`? Or `"\\/\\*.*\\*\\/"`? Please also add a language tag. – Wiktor Stribiżew May 15 '17 at 09:11
  • @"\\/\\*.*\\*\\/", just for some reason it wouldnt display properly here so i added the gaps. – Return-1 May 15 '17 at 09:15
  • 1
    Check [this code](http://stackoverflow.com/a/27880748/3832970) with that regex. Note that `.anchored` makes the regex engine only look for a match at the start of the string. – Wiktor Stribiżew May 15 '17 at 09:16
  • Ok. So you re saying that the regexp pattern "\/\*.*\*\/" is correct and its a problem with the anchored way of searching? – Return-1 May 15 '17 at 09:19
  • I see at least two issues in your pattern. However, if your main concern is the code, your question is a dupe. You did not explain what issues you have with the *pattern*, you say you are *a little confused as how to use this*... this what? To define a literal backslash you need to double it. And you solved it, it is written in your P.S. Then, what is the real problem? – Wiktor Stribiżew May 15 '17 at 09:21
  • Once you realize your pattern is not working as expected, feel free to use [this regex](http://stackoverflow.com/a/36328890/3832970) for Java (same string literal can be used in Swift code). – Wiktor Stribiżew May 15 '17 at 09:32
  • Will keep it in mind. Thank you for helping out. Cheers – Return-1 May 15 '17 at 09:33

0 Answers0