Skip to content

Regular expressions in Swift #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Swift/match.playground/Contents.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import Foundation

let testString = "one 1 two 2 three 3"

let pattern = "[0-9]" // Matching numbers
let nsString = testString as NSString // Cating to NSString to use special methods

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I supposed "Cating" should be "Casting". And maybe not "special" but "specific".


// Trying to initialize regex
do {
let regex = try NSRegularExpression(pattern: pattern, options: [])
Copy link

@Gagnant Gagnant Jun 7, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I propose you to omit options parameter because it has default value []

let results = regex.matches(in: testString, options: [], range: NSMakeRange(0, testString.characters.count)) // Matches
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You must use testString.utf16.count here. Because NSRegularExpression works with NSString, which are utf16 encoded.

let result = results.map { nsString.substring(with: $0.range) }
print(result)
} catch let error as NSError { // Handling exception
print("Invalid regex: \(error.localizedDescription)")
}



4 changes: 4 additions & 0 deletions Swift/match.playground/contents.xcplayground
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='macos'>
<timeline fileName='timeline.xctimeline'/>
</playground>

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file not shown.
17 changes: 17 additions & 0 deletions Swift/replace.playground/Contents.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import Foundation

let helloString = "Hello, World!" // Defining initial string

// Initializing regular expression
var replaceRegExp: NSRegularExpression?

do {
replaceRegExp = try NSRegularExpression(pattern: "World", options: .allowCommentsAndWhitespace)
Copy link

@GreatAndPowerfulKing GreatAndPowerfulKing Jun 7, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you are not stopping an execution on NSRegularExpression initialization failure, you may replace replaceRegExp declaration with: let replaceRegExp = try? NSRegularExpression(pattern: "World", options: .allowCommentsAndWhitespace).

} catch let error as NSError { // Handling exception
print(error.localizedDescription)
}

// Initializing new string with substring, replaced by template
let newString = replaceRegExp?.stringByReplacingMatches(in: helloString, options: .withTransparentBounds, range: NSRange(location: 0, length: helloString.characters.count), withTemplate: "Kitten")

print(newString ?? "Replacing failed", "\n")
4 changes: 4 additions & 0 deletions Swift/replace.playground/contents.xcplayground
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='macos'>
<timeline fileName='timeline.xctimeline'/>
</playground>

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file not shown.
19 changes: 19 additions & 0 deletions Swift/split.playground/Contents.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import Foundation

let initialString = "This-is-string-to-split-by-special-character" // Defining initial string

let splitter = "-" // Defining splitter
let stop = "//"

// Initializing regular expression
var splitRegExp: NSRegularExpression?
do {
splitRegExp = try NSRegularExpression(pattern: splitter, options: .allowCommentsAndWhitespace)
} catch let error as NSError { // Handling exception
print(error.localizedDescription)
}

let modifiedString = splitRegExp?.stringByReplacingMatches(in: initialString, options: .withTransparentBounds, range: NSRange(location: 0, length: initialString.characters.count), withTemplate: stop)

// But in Swift this method can be used
print(modifiedString?.components(separatedBy: stop) ?? "Splitting failed", "\n")
4 changes: 4 additions & 0 deletions Swift/split.playground/contents.xcplayground
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='macos'>
<timeline fileName='timeline.xctimeline'/>
</playground>

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file not shown.