how to print list all first name - list

I had a list with string first name and last name
val dataList = List("Narendra MODI","Amit SHA","Donald TRUMP","Ratan TATA","Abdul KALAM")
I want to print all the first from the list like Narendra,Amit,Donald,Ratan,Abdul
could you please help me on this in scala

The simplest option is to take the initial non-space characters from each string:
dataList.map(_.takeWhile(!_.isSpaceChar))

you can map over your list and use split on space and select the 1st index.
scala> val dataList = List("Narendra MODI","Amit SHA","Donald TRUMP","Ratan TATA","Abdul KALAM")
dataList: List[String] = List(Narendra MODI, Amit SHA, Donald TRUMP, Ratan TATA, Abdul KALAM)
scala> dataList.map( _.split(" ").headOption.getOrElse(None))
res2: List[java.io.Serializable] = List(Narendra, Amit, Donald, Ratan, Abdul)

Related

Find index locations by regex pattern and replace them with a list of indexes in Scala

I have strings in this format:
object[i].base.base_x[i] and I get lists like List(0,1).
I want to use regular expressions in scala to find the match [i] in the given string and replace the first occurance with 0 and the second with 1. Hence getting something like object[0].base.base_x[1].
I have the following code:
val stringWithoutIndex = "object[i].base.base_x[i]" // basically this string is generated dynamically
val indexReplacePattern = raw"\[i\]".r
val indexValues = List(0,1) // list generated dynamically
if(indexValues.nonEmpty){
indexValues.map(row => {
indexReplacePattern.replaceFirstIn(stringWithoutIndex , "[" + row + "]")
})
else stringWithoutIndex
Since String is immutable, I cannot update stringWithoutIndex resulting into an output like List("object[0].base.base_x[i]", "object[1].base.base_x[i]").
I tried looking into StringBuilder but I am not sure how to update it. Also, is there a better way to do this? Suggestions other than regex are also welcome.
You couldloop through the integers in indexValues using foldLeft and pass the string stringWithoutIndex as the start value.
Then use replaceFirst to replace the first match with the current value of indexValues.
If you want to use a regex, you might use a positive lookahead (?=]) and a positive lookbehind (?<=\[) to assert the i is between opening and square brackets.
(?<=\[)i(?=])
For example:
val strRegex = """(?<=\[)i(?=])"""
val res = indexValues.foldLeft(stringWithoutIndex) { (s, row) =>
s.replaceFirst(strRegex, row.toString)
}
See the regex demo | Scala demo
How about this:
scala> val str = "object[i].base.base_x[i]"
str: String = object[i].base.base_x[i]
scala> str.replace('i', '0').replace("base_x[0]", "base_x[1]")
res0: String = object[0].base.base_x[1]
This sounds like a job for foldLeft. No need for the if (indexValues.nonEmpty) check.
indexValues.foldLeft(stringWithoutIndex) { (s, row) =>
indexReplacePattern.replaceFirstIn(s, "[" + row + "]")
}

Capitalize the first string in list using python

I have a list containing strings and I want capitalize the first letter of first string using Python and not the entire list.
I have attempted the following but every first letter in the list is capitalized:
L = ("hello", "what", "is", "your", "name")
LCaps = [str.capitalize(element) for element in L)
print LCaps
So, you want to capitalize the first string and only the first string of a tuple. Use:
>>> L = ("hello", "what", "is", "your", "name")
>>> (L[0].capitalize(),) + L[1:]
('Hello', 'what', 'is', 'your', 'name')
Key points:
Strings have methods. There is no need to use the string module: just use the strings capitalize method.
By running L[0].capitalize(), we capitalize the first string but none of the others.
Because L is a tuple, we can't change the first string in-place. We can however capitalize the first string and concatenate it with the rest.
(L[0].title(),) + L[1:]
You can use title() too.

How to find string in List using Scala?

I have a following list-
List( naa.60a9800042704577762b45634476337a ,
naa.6d867d9c7acd60001aed76eb2c70bd53 ,
naa.600a09804270457a7a5d455448735330)
I want to find a string 42704577762b45634476337a in above list.
Like first string in list contains given string 42704577762b45634476337a.
I dont want to fully match given string with list elements
How do I find string in list using scala??
Looking for a substring
scala> val x = List("123", "abc")
x: List[String] = List(123, abc)
scala> x.find(_.contains("12"))
res0: Option[String] = Some(123)
scala> x.find(_.contains("foo"))
res1: Option[String] = None
If you need an exact match, just replace contains with ==.

Extract numbers from string with rich string magic

I want to extract a list of ID of a string pattern in the following:
{(2),(4),(5),(100)}
Note: no leading or trailing spaces.
The List can have up to 1000 IDs.
I want to use rich string pattern matching to do this. But I tried for 20 minutes with frustration.
Could anyone help me to come up with the correct pattern? Much appreciated!
Here's brute force string manipulation.
scala> "{(2),(4),(5),(100)}".replaceAll("\\(", "").replaceAll("\\)", "").replaceAll("\\{","").replaceAll("\\}","").split(",")
res0: Array[java.lang.String] = Array(2, 4, 5, 100)
Here's a regex as #pst noted in the comments. If you don't want the parentheses change the regular expression to """\d+""".r.
val num = """\(\d+\)""".r
"{(2),(4),(5),(100)}" findAllIn res0
res33: scala.util.matching.Regex.MatchIterator = non-empty iterator
scala> res33.toList
res34: List[String] = List((2), (4), (5), (100))
"{(2),(4),(5),(100)}".split ("[^0-9]").filter(_.length > 0).map (_.toInt)
Split, where char is not part of a number, and only convert non-empty results.
Might be modified to include dots or minus signs.
Use Extractor object:
object MyList {
def apply(l: List[String]): String =
if (l != Nil) "{(" + l.mkString("),(") + ")}"
else "{}"
def unapply(str: String): Some[List[String]] =
Some(
if (str.indexOf("(") > 0)
str.substring(str.indexOf("(") + 1, str.lastIndexOf(")")) split
"\\p{Space}*\\)\\p{Space}*,\\p{Space}*\\(\\p{Space}*" toList
else Nil
)
}
// test
"{(1),(2)}" match { case MyList(l) => l }
// res23: List[String] = List(1, 2)

splitting a string into a list in specman

Supposing I have a string:
str = “ab,cd,ef”
and I want to split it into a list
lst = [“ab”,”cd”,ef”]
How can I do it best, assuming that I don’t know ahead of time how many items are in the string?
Basically I'm looking for a specman equivalent to Perl's:
$str = "ab,cd,ef";
#lst = split /,/, $str;
str_split is what you want.
From Specman 6.1 docs:
str_split(str: string, regular-exp: string): list of string
Syntax Example
var s: list of string = str_split("first-second-third", "-");