Working with text
Ring already has good text functions. This lesson shows when to use Ring's own, and what .NET adds — joining, formatting, building long texts, regular expressions, Base64 and encodings.
What you will learn#
- which text jobs Ring does by itself and which need .NET,
Stringhelpers (Join,Format,Compare,IsNullOrWhiteSpace),StringBuilderfor long texts,- regular expressions with
Regex, - Base64 and UTF-8.
Texts between Ring and .NET#
A Ring text is a .NET string as soon as you pass it to a .NET method. A .NET method that returns a string gives you a Ring text.
One rule is important: a .NET string is not an object in Ring, it is just a Ring text. That means a .NET instance method such as Trim() is not called on it. For those jobs Ring has its own functions: trim(), upper(), lower(), substr(), left(). Use Ring's functions for the basics, and .NET for what Ring does not include. The static methods of the class String (Join, Format...) work fine because they take the text as an argument.
The program#
# working with text - Ring text functions, String helpers, StringBuilder, regular expressions, encodings
load "dotnet.ring"
using {
"System"
"System.Text"
"System.Text.RegularExpressions"
"System.Globalization"
}
func main
# Ring already has many text functions: use them for the basics
cSentence = " The quick brown fox "
? "Ring trim/upper : [" + upper(trim(cSentence)) + "]"
aWords = str2list(substr(trim(cSentence)," ",nl))
? "Ring words : " + len(aWords)
# .NET adds more helpers. String's static methods:
oString = new String()
? "Join : " + oString.Join([ :separator = "-", :value = aWords ])
? "Format : " + oString.Format([ :format = "{0} has {1} items", :arg0 = "The list", :arg1 = 3 ])
? "Empty or blank? : " + oString.IsNullOrWhiteSpace(" ")
? "Compare (a < b) : " + oString.Compare([ :strA = "apple", :strB = "banana" ])
# Title case needs the culture of the user
oText = new CultureInfo("en-US").TextInfo
? "Title case : " + oText.ToTitleCase("ring meets dot net")
# Building a long text efficiently: StringBuilder
oBuilder = new StringBuilder("")
for nLine = 1 to 3
oBuilder.Append("line " + nLine)
oBuilder.AppendLine(NULL)
next
? "StringBuilder : " + len(oBuilder.ToString()) + " characters"
# Numbers in other bases, and Base64
? "255 in hex : " + new Convert().Format([ :value = 255, :toBase = 16 ])
? "Base64 : " + new Convert().ToBase64String("Ring")
# Regular expressions: patterns for text
oEmail = new Regex("[a-z]+@[a-z]+\.com")
cMail = "write to ann@example.com or bob@test.com today"
oMatches = oEmail.Matches(cMail)
? "E-mails found : " + oMatches.Count
for nIndex = 0 to oMatches.Count - 1
? " " + oMatches.Item(nIndex).Value
next
? "Replaced : " + oEmail.Replace([ :input = cMail, :replacement = "<hidden>" ])
? "Is it a number? : " + new Regex("^[0-9]+$").IsMatch("12345") + " " + new Regex("^[0-9]+$").IsMatch("12x45")
# Encodings: text <-> bytes
oUtf8 = new Encoding().UTF8
? "UTF-8 bytes : " + len(oUtf8.GetBytes("Ring")) + " for Ring, " + len(oUtf8.GetBytes("Ring é")) + " with an accent"Ring trim/upper : [THE QUICK BROWN FOX]
Ring words : 4
Join : The-quick-brown-fox
Format : The list has 3 items
Empty or blank? : 1
Compare (a < b) : -1
Title case : Ring Meets Dot Net
StringBuilder : 24 characters
255 in hex : ff
Base64 : UmluZw==
E-mails found : 2
ann@example.com
bob@test.com
Replaced : write to <hidden> or <hidden> today
Is it a number? : 1 0
UTF-8 bytes : 4 for Ring, 7 with an accentHow it works#
Ring first#
upper(trim(cSentence)) is Ring. The words are found by turning spaces into new lines and reading each line as an item: str2list(substr(cSentence," ",nl)).
String's static helpers#
| Call | Result |
|---|---|
oString.Join([ :separator = "-", :value = aWords ]) | all the words with - between them |
oString.Format([ :format = "{0} has {1} items", :arg0 = "The list", :arg1 = 3 ]) | {0}, {1} are replaced by the arguments |
oString.IsNullOrWhiteSpace(" ") | true for empty or blank text |
oString.Compare([ :strA = "apple", :strB = "banana" ]) | -1 if the first sorts before the second, 0 if equal, 1 if after |
Join, Format and Compare exist in several forms, so in Ring each is one method that takes a list of named values (the names are the parameter names in the .NET documentation): for Format the pattern (format) and the values (arg0, arg1).
Title case needs a culture#
Capital letters depend on the language. new CultureInfo("en-US").TextInfo.ToTitleCase(...) makes Ring Meets Dot Net. A culture describes how a language writes text, numbers and dates.
StringBuilder for long texts#
Adding to a Ring text in a loop copies the text every time. A StringBuilder grows in place, so use it when you build a big text (a report, a file). AppendLine(NULL) adds a new line; NULL means "no argument" for a method that has several versions.
Base64 and numbers in other bases#
Convert.Format([ :value = 255, :toBase = 16 ]) writes a number in base 16 (ff). Convert.ToBase64String("Ring") encodes bytes as text (UmluZw==); Base64 is how binary data is sent in e-mail and web pages.
Regular expressions#
A regular expression (regex) is a pattern for text. [a-z]+@[a-z]+\.com means "letters, an @, letters, .com". Regex can:
| Method | Job |
|---|---|
Matches(text) | find all the places that match |
Replace([ :input = text, :replacement = r ]) | replace every match |
IsMatch(text) | does the text match? |
^[0-9]+$ means "only digits from the start to the end": the text 12345 matches, 12x45 does not.
Encodings#
A computer stores bytes, not letters. An encoding says how letters become bytes. UTF-8 is the standard: Ring is 4 bytes, but Ring é is 7, because é needs two bytes.
What you learned#
- Use Ring's own functions for basic text work; call
String's static helpers when you needJoin,Format,Compare. StringBuilderbuilds long texts efficiently.Regexfinds, tests and replaces patterns.- Text, bytes and encodings are different things.
Exercises#
- Use
Regexto find every number in"I have 3 cats and 12 fish". (Pattern:[0-9]+.) - Use
String.Formatwith a list of named values to printAnn is 31 years oldfrom the values"Ann"and31. - Write a function
isEmail(cText)that returns true whenRegex.IsMatchsays the text looks likename@site.com. - Encode your name to Base64 with
Convert.ToBase64String, then decode it withConvert.FromBase64String.