How do I remove newlines from a String in Dart? - dart

How do I remove the newlines from a string in Dart?
For instance, I want to convert:
"hello\nworld"
to
"hello world"

You can use replaceAll(pattern, replacement):
main() {
var multiline = "hello\nworld";
var singleline = multiline.replaceAll("\n", " ");
print(singleline);
}

#SethLadd's answer is correct, but in a very basic example.
In the case of a multiline input with text like:
Hello, world!
{\n}
I like things:
- cats
- dogs
{\n}
I like cats, alot
{\n}
{\n}
and more cats
{\n}
{\n}
{\n}
. (ignore this dot)
In the case of the above, your string is represented like this:
Hello, world!\n\nI like things:\n- cats\n- dogs\n\nI like cats, alot\n\n\nand more cats\n\n\n\n
Using #SethLadd's solution, I will be left with:
Hello, world!I like things:- cats- dogsI like cats, alotand more cats
which is certainly not the desired outcome. I suggest using the commonly used regex approach of to tackle the problem.
Calling .trim() will remove the last 4 \n (and any \n infront too).
If one wishes, you could limit new lines to a single open line with something like
text.trim().replaceAll(RegExp(r'(\n){3,}'), "\n\n")

Related

How to find a word in a single long string?

I want to be able to copy and paste a large string of words from say a text document where there are spaces, returns and not commas between each and every word. Then i want to be able to take out each word individually and put them in a table for example...
input:
please i need help
output:
{1, "please"},
{2, "i"},
{3, "need"},
{4, "help"}
(i will have the table already made with the second column set to like " ")
havent tried anything yet as nothing has come to mind and all i could think of was using gsub to turn spaces into commas and find a solution from there but again i dont think that would work out so well.
Your delimiters are spaces ( ), commas (,) and newlines (\n, sometimes \r\n or \r, the latter very rarely). You now want to find words delimited by these delimiters. A word is a sequence of one or more non-delimiter characters. This trivially translates to a Lua pattern which can be fed into gmatch. Paired with a loop & inserting the matches in a table you get the following:
local words = {}
for word in input:gmatch"[^ ,\r\n]+" do
table.insert(words, word)
end
if you know that your words are gonna be in your locale-specific character set (usually ASCII or extended ASCII), you can use Lua's %w character class for matching sequences of alphanumeric characters:
local words = {}
for word in input:gmatch"%w+" do
table.insert(words, word)
end
Note: The resulting table will be in "list" form:
{
[1] = "first",
[2] = "second",
[3] = "third",
}
(for which {"first", "second", "third"} would be shorthand)
I don't see any good reasons for the table format you have described, but it can be trivially created by inserting tables instead of strings into the list.

extract data from string in lua - SubStrings and Numbers

I'm trying to phrase a string for a hobby project and I'm self taught from code snips from this site and having a hard time working out this problem. I hope you guys can help.
I have a large string, containing many lines, and each line has a certain format.
I can get each line in the string using this code...
for line in string.gmatch(deckData,'[^\r\n]+') do
print(line) end
Each line looks something like this...
3x Rivendell Minstrel (The Hunt for Gollum)
What I am trying to do is make a table that looks something like this for the above line.
table = {}
table['The Hunt for Gollum'].card = 'Rivendell Minstrel'
table['The Hunt for Gollum'].count = 3
So my thinking was to extract everything inside the parentheses, then extract the numeric vale. Then delete the first 4 chars in the line, as it will always be '1x ', '2x ' or '3x '
I have tried a bunch of things.. like this...
word=str:match("%((%a+)%)")
but it errors if there are spaces...
my test code looks like this at the moment...
line = '3x Rivendell Minstrel (The Hunt for Gollum)'
num = line:gsub('%D+', '')
print(num) -- Prints "3"
card2Fetch = string.sub(line, 5)
print(card2Fetch) -- Prints "Rivendell Minstrel (The Hunt for Gollum)"
key = string.gsub(card2Fetch, "%s+", "") -- Remove all Spaces
key=key:match("%((%a+)%)") -- Fetch between ()s
print(key) -- Prints "TheHuntforGollum"
Any ideas how to get the "The Hunt for Gollum" text out of there including the spaces?
Try a single pattern capturing all fields:
x,y,z=line:match("(%d+)x%s+(.-)%s+%((.*)%)")
t = {}
t[z] = {}
t[z].card = y
t[z].count = x
The pattern reads: capture a run of digits before x, skip whitespace, capture everything until whitespace followed by open parenthesis, and finally capture everything until a close parenthesis.

Compare a string by giving two possibilities for each character in Swift [duplicate]

I need to compare a string by giving two possibilities for each character in the string in an (if) statement eg:
let str = "2 3 1 2"
if str == "(1||2) (2||3) (1||2) (1||2)" {
//Do Something
}
I know the code is not written correctly, but just to understand what I mean.
I used to use (Like Operator) in VB eg:
Dim s As String = "2 3 1 2"
If s Like "[1-2] [3-4] [2-3] [1-2]" Or s Like "[1-2] [1-2] [2-3] 2" Then
//Do something
End If
I couldn't find anything similar in swift.
Please help, Thank you.
The problem you describe is crying out to solved using regular expressions.
Last time I looked, Swift did not support regular expressions, but it does allow use of NSRegularExpression. See Regex in Swift for an example of a Regex class.
So you'd end up writing something like
if Regex("[12] [23] [12] [12]").test("2 3 1 2") {
println("matches pattern")
}
Another blog post on this topic is Clean Regular Expressions In Swift.
Looks like what you are asking for is support for regular expressions. They don't exist directly in Swift (yet?). But you might want to have a look at RegEx in Swift? and http://nomothetis.svbtle.com/clean-regular-expressions-using-conversions .

Compare a string by giving two possibilities for each character in Swift

I need to compare a string by giving two possibilities for each character in the string in an (if) statement eg:
let str = "2 3 1 2"
if str == "(1||2) (2||3) (1||2) (1||2)" {
//Do Something
}
I know the code is not written correctly, but just to understand what I mean.
I used to use (Like Operator) in VB eg:
Dim s As String = "2 3 1 2"
If s Like "[1-2] [3-4] [2-3] [1-2]" Or s Like "[1-2] [1-2] [2-3] 2" Then
//Do something
End If
I couldn't find anything similar in swift.
Please help, Thank you.
The problem you describe is crying out to solved using regular expressions.
Last time I looked, Swift did not support regular expressions, but it does allow use of NSRegularExpression. See Regex in Swift for an example of a Regex class.
So you'd end up writing something like
if Regex("[12] [23] [12] [12]").test("2 3 1 2") {
println("matches pattern")
}
Another blog post on this topic is Clean Regular Expressions In Swift.
Looks like what you are asking for is support for regular expressions. They don't exist directly in Swift (yet?). But you might want to have a look at RegEx in Swift? and http://nomothetis.svbtle.com/clean-regular-expressions-using-conversions .

Split lua string into characters

I only found this related to what I am looking for: Split string by count of characters but it is not useful for what I mean.
I have a string variable, which is an ammount of 3 numbers (can be from 000 to 999). I need to separate each of the numbers (characters) and get them into a table.
I am programming for a game mod which uses lua, and it has some extra functions. If you could help me to make it using: http://wiki.multitheftauto.com/wiki/Split would be amazing, but any other way is ok too.
Thanks in advance
Corrected to what the OP wanted to ask:
To just split a 3-digit number in 3 numbers, that's even easier:
s='429'
c1,c2,c3=s:match('(%d)(%d)(%d)')
t={tonumber(c1),tonumber(c2),tonumber(c3)}
The answer to "How do I split a long string composed of 3 digit numbers":
This is trivial. You might take a look at the gmatch function in the reference manual:
s="123456789"
res={}
for num in s:gmatch('%d%d%d') do
res[#res+1]=tonumber(num)
end
or if you don't like looping:
res={}
s:gsub('%d%d%d',function(n)res[#res+1]=tonumber(n)end)
I was looking for something like this, but avoiding looping - and hopefully having it as one-liner. Eventually, I found this example from lua-users wiki: Split Join:
fields = {str:match((str:gsub("[^"..sep.."]*"..sep, "([^"..sep.."]*)"..sep)))}
... which is exactly the kind of syntax I'd like - one liner, returns a table - except, I don't really understand what is going on :/ Still, after some poking about, I managed to find the right syntax to split into characters with this idiom, which apparently is:
fields = { str:match( (str:gsub(".", "(.)")) ) }
I guess, what happens is that gsub basically puts parenthesis '(.)' around each character '.' - so that match would consider those as a separate match unit, and "extract" them as separate units as well... But I still don't get why is there extra pair of parenthesis around the str:gsub(".", "(.)") piece.
I tested this with Lua5.1:
str = "a - b - c"
fields = { str:match( (str:gsub(".", "(.)")) ) }
print(table_print(fields))
... where table_print is from lua-users wiki: Table Serialization; and this code prints:
"a"
" "
"-"
" "
"b"
" "
"-"
" "
"c"

Resources