I have a string val str = "London\\/India\\/chaina\\/" wanted to replace to "London_India_chaina_"
If I am doing
str.replaceAll("\\\/","_")
getting "London\_India\_chaina\_"
Scala String is in essence java String object.
scala> val str = "London/India/chaina/"
str: String = London/India/chaina/
scala> str.replace("/", "_")
res0: String = London_India_chaina_
You are missing one \ character in the first parameter of replaceAll :
object Replace {
def main(args : Array[String]) = {
var str = "London\\/India\\/chaina\\/"
println(str)
println(str.replaceAll("\\\\/","_"))
}
}
Output :
London\/India\/chaina\/
London_India_chaina_
Operating on the string as a sequence of characters,
str map {
case '/' => '_'
case c => c
}
The second case matches any other character different from '/'.
Try this:
val str = "London\\/India\\/chaina\\/"
str.replaceAll("""\\\\/""","_")
Related
I have a string like "debug#compile". Now, my end goal is to convert first letter of each word to uppercase. So, at last I should get "Debug#Compile" where 'D' and 'C' are converted to uppercase.
My logic:
1) I have to split the string on the basis of delimiters. It will be special characters.So, I have to check everytime.
2) After that I would convert each word's first letter to upper case and then using map I would join it again.
I am trying my best but not able to design the code for this. Can anyone help me in this. Even hints would help!
Below is my code:
object WordCase {
def main(args: Array[String]) {
val s="siddhesh#kalgaonkar"
var b=""
val delimeters= Array("#","_")
if(delimeters(0)=="#")
{
b=s.split(delimeters(0).toString).map(_.capitalize).mkString(delimeters(0).toString())
}
else if(delimeters(0)=="_")
{
b=s.split(delimeters(0).toString).map(_.capitalize).mkString(delimeters(0).toString())
}
else{
println("Non-Standard String")
}
println(b)
}
}
My code capitalizes the first letter of every word in capital on the basis of constant delimeter and have to merge it. Here for the first part i.e "#" it capitalizes first letter of every words but it fails for the second case i.e "_". Am I makinig any silly mistakes in looping?
scala> val s="siddhesh#kalgaonkar"
scala> val specialChar = (s.split("[a-zA-Z0-9]") filterNot Seq("").contains).mkString
scala> s.replaceAll("[^a-zA-Z]+"," ").split(" ").map(_.capitalize).mkString(",").replaceAll(",",specialChar)
res41: String = Siddhesh#Kalgaonkar
You can manage multiple special char in this way
scala> val s="siddhesh_kalgaonkar"
s: String = siddhesh_kalgaonkar
scala> val specialChar = (s.split("[a-zA-Z0-9]") filterNot Seq("").contains).mkString
specialChar: String = _
scala> s.replaceAll("[^a-zA-Z]+"," ").split(" ").map(_.capitalize).mkString(",").replaceAll(",",specialChar)
res42: String = Siddhesh_Kalgaonkar
I solved it the easy way:
object WordCase {
def main(args: Array[String]) {
val s = "siddhesh_kalgaonkar"
var b = s.replaceAll("[^a-zA-Z]+", " ").split(" ").map(_.capitalize).mkString(" ") //Replacing delimiters with space and capitalizing first letter of each word
val c=b.indexOf(" ") //Getting index of space
val d=s.charAt(c).toString // Getting delimiter character from the original string
val output=b.replace(" ", d) //Now replacing space with the delimiter character in the modified string i.e 'b'
println(output)
}
}
My code is as follows:
class HuffmanNode(val chars: String, val occurrences: Int) {
override def toString: String = "{" + chars + "|" + occurrences + "}"
def absoluteValue: Int = occurrences
def getChars: String = chars
def getOccurrences: String = occurrences.toString
}
object HuffmanNode {
def apply(chars: String, occurrences: Int): HuffmanNode = {
new HuffmanNode(chars, occurrences)
}
}
I'm trying to create a list of HuffmanNode, e.g.:
val PQ: List[HuffmanNode] = List(HuffmanNode("a", 3), HuffmanNode("b", 3))
How do I access the methods inside the HuffmanNode?
I tried doing this:
PQ(0).getChars
But I get an error saying, unable to resolve symbol getChars.
What could the problem be?
Your code does not compile. If I would hazard a guess I would imagine that you are using a list of the singleton instead of an instance of the class (the singleton does not have a getChars method, only the apply).
If you change code as I suggested in edit, there is no problem to invoke getChars method:
class HuffmanNode(val chars: String, val occurrences: Int) {
override def toString: String = "{" + chars + "|" + occurrences + "}"
def absoluteValue: Int = occurrences
def getChars: String = chars
def getOccurrences: String = occurrences.toString
}
object HuffmanNode {
def apply(chars: String, occurrences: Int): HuffmanNode = {
new HuffmanNode(chars, occurrences)
}
}
val PQ: List[HuffmanNode] = List(HuffmanNode("a", 3), HuffmanNode("b", 3))
PQ(1).getChars
I got:
PQ: List[HuffmanNode] = List({a|3}, {b|3})
res0: String = b
However I needed (just to test) remove keyword override from absoluteValue method.
As pointed out by #Assaf Mendelson you refer to the singleton object instead of instance of the class.
In order to fix you code you should create instance of the class instead like:
val PQ = List(HuffmanNode("blabla", 2))
val chars = PQ(0).getChars // now compiles
I have below string and I want to extract only List((asdf, asdf), (fff,qqq)) from the string, line has many other characters before and after the part I want to extract.
some garbage string PARAMS=List((foo, bar), (foo1, bar1)) some garbage string
I have tried these regex
(?:PARAMS)=(List\((.*?)\))
(?:PARAMS)=(List\(([^)]+)\))
but it gives me below output in group(1):
List((foo, bar)
regex .*List\((.*)\).* works
Using Scala regex and pattern matching together and then split with any of ( , ) and then group
regex contains extractors
val r = """.*List\((.*)\).*""".r
pattern matching using extractor in regex
val result = str match {
case r(value) => value
case _ => ""
}
Then split using any of ( or , or ) and then group
result.split("""[(|,|)]""").filterNot(s => s.isEmpty || s.trim.isEmpty)
.grouped(2)
.toList
.map(pair => (pair(0), pair(1))).toList
Scala REPL
scala> val str = """some garbage string PARAMS=List((foo, bar), (foo1, bar1)) some garbage string"""
str: String = "some garbage string PARAMS=List((foo, bar), (foo1, bar1)) some garbage string"
scala> val r = """.*List\((.*)\).*""".r
r: util.matching.Regex = .*List\((.*)\).*
scala> val result = str match {
case r(value) => value
case _ => ""
}
result: String = "(foo, bar), (foo1, bar1)"
scala> result.split("""[(|,|)]""").filterNot(s => s.isEmpty || s.trim.isEmpty).grouped(2).toList.map(pair => (pair(0), pair(1))).toList
res46: List[(String, String)] = List(("foo", " bar"), ("foo1", " bar1"))
In this Scala code I'm trying to analyze a string that contains a sum (such as 12+3+5) and return the result (20). I'm using regex to extract the first digit and parse the trail to be added recursively. My issue is that since the regex returns a String, I cannot add up the numbers. Any ideas?
object TestRecursive extends App {
val plus = """(\w*)\+(\w*)""".r
println(parse("12+3+5"))
def parse(str: String) : String = str match {
// sum
case plus(head, trail) => parse(head) + parse(trail)
case _ => str
}
}
You might want to use the parser combinators for an application like this.
"""(\w*)\+(\w*)""".r also matches "+" or "23+" or "4 +5" // but captures it only in the first group.
what you could do might be
scala> val numbers = "[+-]?\\d+"
numbers: String = [+-]?\d+
^
scala> numbers.r.findAllIn("1+2-3+42").map(_.toInt).reduce(_ + _)
res4: Int = 42
scala> numbers.r.findAllIn("12+3+5").map(_.toInt).reduce(_ + _)
res5: Int = 20
I am writing a macro m(expr: String), where expr is an expression in some language (not Scala):
m("SOME EXPRESSION")
m("""
SOME EXPRESSION
""")
When I am parsing the expression I would like to report error messages with proper locations in the source file. To achieve this I should know the location of the string literal itself and the number of quotes of the literal (3 or 1). Unfortunately, I did not find any method that returns the number of quotes of the literal:
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context
object Temp {
def m(s: String) : String = macro mImpl
def mImpl(context: Context)(s: context.Expr[String]): context.universe.Tree = {
import context.universe._
s match {
case l # Literal(Constant(p: String)) =>
if (l.<TRIPLE QUOTES>) {
...
} else {
...
}
case _ =>
context.abort(context.enclosingPosition, "The argument of m must be a string literal")
}
}
}
What should I put instead of <TRIPLE QUOTES>?
The only way i can think of is to access the source file and check for triple quotes:
l.tree.pos.source.content.startsWith("\"\"\"",l.tree.pos.start)
You need also to edit your matching case:
case l # Expr(Literal(Constant(p: String))) =>
Here the version with some explanation:
val tree: context.universe.Tree = l.tree
val pos: scala.reflect.api.Position = tree.pos
val source: scala.reflect.internal.util.SourceFile = pos.source
val content: Array[Char] = source.content
val start: Int = pos.start
val isTriple: Boolean = content.startsWith("\"\"\"",start)