Swift Xcode6 beta6 regex - xcode

I want to get the characters using regex
I want to get "CDE"
var results : NSMutableArray;
var baseString = "ABCDEFG"
var regexp = NSRegularExpression(pattern: "AB.*?FG", options: nil, error: nil)
var match : NSArray = regexp.matchesInString(baseString, options: nil, range: NSMakeRange(0,countElements(baseString)));
for matches in match {
results.addObject(sampleString.substringWithRange(matches.rangeAtIndex(2)));
}
println(results);//print"CDE"
but I get error.
ERROR→
results.addObject(sampleString.substringWithRange(matches.rangeAtIndex(2)));
NSRange' is not convertible to 'Range<String.Index>'
my english isn't good.sorry..
please help me...

The regular expression is incorrect, the match will be the entire string. Instead use: (?<=AB).*?(?=FG).
Documantation: ICU User Guide Regular Expressions
Notes:
(?<=AB) means preceded by AB
(?=FG) means followed by FG
These do not capture the matched portion.
Example code:
var baseString = "ABCDEFG"
var pattern = "(?<=AB).*?(?=FG)"
if let range = baseString.rangeOfString(pattern, options: .RegularExpressionSearch) {
let found = baseString.substringWithRange(range)
println("found: \(found)")
}
Output:
found: CDE

Related

regex with quotation mark

How do I use .js to regex out the quotation marks in the following string?
var wtfx = "<div>ExternalClass=5"</div>44FB";
var wtf = /<div>ExternalClass.*>/;
wtf = wtfx.replace(wtf, "");
alert(wtf);
shows this does not work. If I take the '"' out then it does. How do I 'escape' the quote?
for example I'd like to use reg ex on the above wtf string to yield only the string 44FB.
not getting this.
The following Code will alert "44FB":
var wtfx = "<div>ExternalClass=5\"</div>44FB";
var wtf = /<div>ExternalClass.*>/;
wtf = wtfx.replace(wtf, "");
alert(wtf);
The only change is the Backslash before the Quotationmark in line 1.
However, I'm not 100% sure if that is what you want. Feel free to write a comment if you need another result.

best way to find substring in ruby using regular expression

I have a string https://stackverflow.com. I want a new string that contains the domain from the given string using regular expressions.
Example:
x = "https://stackverflow.com"
newstring = "stackoverflow.com"
Example 2:
x = "https://www.stackverflow.com"
newstring = "www.stackoverflow.com"
"https://stackverflow.com"[/(?<=:\/\/).*/]
#⇒ "stackverflow.com"
(?<=..) is a positive lookbehind.
If string = "http://stackoverflow.com",
a really easy way is string.split("http://")[1]. But this isn't regex.
A regex solution would be as follows:
string.scan(/^http:\/\/(.+)$/).flatten.first
To explain:
String#scan returns the first match of the regex.
The regex:
^ matches beginning of line
http: matches those characters
\/\/ matches //
(.+) sets a "match group" containing any number of any characters. This is the value returned by the scan.
$ matches end of line
.flatten.first extracts the results from String#scan, which in this case returns a nested array.
You might want to try this:
#!/usr/bin/env ruby
str = "https://stackoverflow.com"
if mtch = str.match(/(?::\/\/)(/S)/)
f1 = mtch.captures
end
There are two capturing groups in the match method: the first one is a non-capturing group referring to your search pattern and the second one referring to everything else afterwards. After that, the captures method will assign the desired result to f1.
I hope this solves your problem.

removeRange() function gives empty string in Swift 2

The removeRange: is giving me an empty string in Swift 2 and I don't understand why.
The example in the apple documentation is:
var welcome = "hello!"
let range = welcome.endIndex.advancedBy(-6)..<welcome.endIndex
welcome.removeRange(range)
//I get "" as result rather than "hello" where the exclamation mark is removed
What could be the problem?
You start at the endIndex and then you go back by 6. You are now at the beginning of the word. Then you make a range to the end index and you remove the content of this range: of course there's nothing left. :)
For example, it could be this instead:
var welcome = "hello!"
let range = welcome.endIndex.advancedBy(-1)..<welcome.endIndex
welcome.removeRange(range)
Or this:
var welcome = "hello!"
let range = welcome.startIndex.advancedBy(5)..<welcome.endIndex
welcome.removeRange(range)
There's many possible combinations.
the string in apple documentation is
at the time of remove range
var welcome = "hello there!"
The value of welcome.endIndex is 6 so advancedBy(-6) means it goes to 0. Then the range = 0..<6 that means the the range cover the whole string.
If you want "hello" then change only advancedBy(-1).
var welcome = "hello!"
let range = welcome.endIndex.advancedBy(-1)..<welcome.endIndex
welcome.removeRange(range)

Manipulating strings with Swift

I am trying to divide a String in Swift. I have the following string
Program - /path/to/file.doc
I want to get three informations out of this string
Program
/path/to/file.doc
file.doc
I began with the following solution
var str = "Program - /path/to/file.doc"
let indi = str.rangeOfString("-")?.startIndex
let subString = str.substringWithRange(Range<String.Index>(start: str.startIndex, end: indi!))
let subString2 = str.substringWithRange(Range<String.Index>(start: indi!, end: str.endIndex))
This gives me the results
"Program "and
"- /path/to/file.doc"
But how can I get file.doc after the last /?
How Can i increase/decrease and range index to avoid blank spaces?
Yes, sidyll's suggestion is correct, it's a very common practice to get components of Unix path by converting it to NSURL. You may want to write something like this:
var str = "Program - /path/to/file.doc"
if let indi = str.rangeOfString(" - ")?.startIndex {
let subString = str.substringWithRange(Range<String.Index>(start: str.startIndex, end: indi))
let subString2 = str.substringWithRange(Range<String.Index>(start: indi, end: str.endIndex))
let fileName = NSURL(string: subString2).lastPathComponent()
}
I strongly suggest you don't do force unwrap like this. Consider situation if this code will work with string without a particular pattern, for example empty string. Correct, runtime error.

Dictionary Optional? Confusion in swift

I know there are a lot of posts on this, but I can't seem to figure out what's going on. The dictionary prints fine. It has a list of words with the number of letters for that word as the value. I want to check if another string is in the list. I read a bunch on optionals, but apparently I'm missing something. I think it has to do with that of course.
let path = NSBundle.mainBundle().pathForResource("wordlist", ofType: "txt")
var content = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil)?.componentsSeparatedByString("\n")
var myDict = [String : Int]()
let compareWord : String? = "TEST"
if let content = content {
for word in 100 ..< 105
{
myDict[content[word]] = countElements(content[word])
}
}
println("\(myDict)")
var num : Int? = 0
println("Num: \(myDict[compareWord!])")
if let num : Int = myDict[compareWord!] {
println("\(compareWord) is a word with \(num) letters")
}
else
{
println("Wasn't a word")
}
**** Updated with a bit more detail of the code.
Here is what I get when I print a section of the dictionary.
[ABBOTSHIPS
: 11, ABBREVIATED
: 12, ABBOTS
: 7, ABBOTSHIP
: 10, ABBREVIATE
: 11]
If I set the test word to one of them I always get nil when checking for it. It seems to work fine when I manually type things in under the playground.
Ensure that componentsSeparatedByString("\n") doesn't leave any other character, such as \r, at the beginning or end of each extracted strings.

Resources