Flutter - How to replace text (containing "id") with title for the id? - string

I have text like this:
Forecaster Strongly disagree \n\nSomething else is going to happen\n\nExample:-\n\n#:hashtag/424 \n#:hashtag/2818 ",
I need to get 424 and 2818 (which are ids) and find titles for those ids and replace #:hashtag/424 with #Title1
How do I manipulate string for this?

You can use a regular expression like this:
RegExp exp = RegExp(r'#:hashtag\/(\d+)');
String test = "Forecaster Strongly disagree \n\nSomething else is going to happen\n\nExample:-\n\n#:hashtag/424 \n#:hashtag/2818";
final matches = exp.allMatches(test);
if(matches.isNotEmpty){
print (matches.first[0]!.split('/').last);
}
//prints 424
some additional null checks will probably be nececssary depending on what you can expect from the input string
To replace the IDs you could use the replaceAllMapped method like this:
test.replaceAllMapped(exp, (match) => match[0]!.split('/').first + '/#Title1');

Related

I can't get two String values in one string using templates

I got some function:
private fun selectHometown() = File("data/towns.txt")
.readText()
.split("\n")
.shuffled()
.first()
And if I try to get or print some string with the 2 values obtained from this function, the first value disappears. For example:
println("${selectHometown() ${selectHometown() }")
Will only print one city name, while I expect two. I guess the problem is related to string concatenation in Kotlin. Of course, I can get the desired result in a different way, but I'm wondering why this one doesn't work.
Windows way of terminating a line is to use "\r\n" so use it as delimiter :
private fun selectHometown() = File("data/towns.txt")
.readText()
.split("\r\n")
.shuffled()
.first()
println("${selectHometown()} ${selectHometown()}")

groovy iterate through list of key and value

I have this list:
service_name_status=[a-service=INSTALL, b-service=UPGRADE, C-service=UPGRADE, D-service=INSTALL]
And I need to iterate through this list so the first element will be the value of a parameter called "SERVICE_NAME" and the second element will be the value of a parameter called "HELM_COMMAND",
after asserting those values to the parameters I will run my command that uses those parameters and then continue the next items on the list which should replace the values of the parameters with items 3 and 4 and so on.
So what I am looking for is something like that:
def service_name_status=[a-service=INSTALL, b-service=UPGRADE, C-service=UPGRADE, D-service=INSTALL]
def SERVICE_NAME
def HELM_COMMAND
for(x in service_name_status){
SERVICE_NAME=x(0,2,4,6,8...)
HELM_COMMAND=x(1,3,5,7,9...)
println SERVICE_NAME=$SERVICE_NAME
println HELM_COMMAND=$HELM_COMMAND
}
the output should be:
SERVICE_NAME=a-service
HELM_COMMAND=INSTALL
SERVICE_NAME=b-service
HELM_COMMAND=UPGRADE
SERVICE_NAME=c-service
HELM_COMMAND=UPGRADE
SERVICE_NAME=d-service
HELM_COMMAND=INSTALL
and so on...
I couldn't find anything that takes any other element in groovy, any help will be appreciated.
The collection you want is a Map, not a List.
Take note of the quotes in the map, the values are strings so you need the quotes or it won't work. You may have to change that at the source where your data comes from.
I kept your all caps variable names so you will feel at home, but they are not the convention.
Note the list iteration with .each(key, value)
This will work:
Map service_name_status = ['a-service':'INSTALL', 'b-service':'UPGRADE', 'C-service':'UPGRADE', 'D-service':'INSTALL']
service_name_status.each {SERVICE_NAME, HELM_COMMAND ->
println "SERVICE_NAME=${SERVICE_NAME}"
println "HELM_COMMAND=${HELM_COMMAND}"
}
EDIT:
The following can be used to convert that to a map. Be careful, the replaceAll part is fragile and depends on the data to always look the same.
//assuming you can have it in a string like this
String st = "[a-service=INSTALL, b-service=UPGRADE, C-service=UPGRADE, D-service=INSTALL]"
//this part is dependent on format
String mpStr = st.replaceAll(/\[/, "['")
.replaceAll(/=/, "':'")
.replaceAll(/]/, "']")
.replaceAll(/, /, "', '")
println mpStr
//convert the properly formatted string to a map
Map mp = evaluate(mpStr)
assert mp instanceof java.util.LinkedHashMap

String formating and store the values

I have a string similar to below
"OPR_NAME:CODE=value,:DESC=value,:NUMBER=value,:INITIATOR=value,:RESP"
I am using StringTokenizer to split the string into tokens based on the delimiter(,:),I need the values of
CODE,DESC and NUMBER.
Can someone pls tell how to achieve this ? The values may come in random order in my string
For eg my string may be like below as well :
"OPR_NAME:DESC=value,:NUMBER=value,:CODE=value,:INITIATOR=value,:RESP" and still it should be able to fetch the values.
I did below to split the string into tokens
StringTokenizer st = new StringTokenizer(str,",:");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
But not sure how to store these tokens to just get the value of 3 fields as mentioned above.
Thanks !!
Okay so what I meant is, detect where is the "=" and then apply a substring to get the value you want.
rough example
System.out.println(st.nextToken().substring(st.nextToken().indexOf('=')+1,st.nextToken().length()));
Use split instead :
String[] parts = X.split(",:");
for (String x:parts) {
System.out.println(x.substring(x.indexOf('=')+1));
}

C# 4.0 function to check for first four characters in the string

I need to validate for valid code name.
So, my string can have values like below:
String test = "C000. ", "C010. ", "C020. ", "C030. ", "CA00. ","C0B0. ","C00C. "
So my function needs to validate below conditions:
It should start with C
After that next 3 characters should be numeric before .
Rest it can be anything.
So in above string values, only ["C000.", "C010.", "C020.", "C030."] are valid ones.
EDIT:
Below is the code I tried:
if (nameObject.Title.StartsWith(String.Format("^[C][0-9]{3}$",nameObject.Title)))
I'd suggest a regex, for example (written off the top of my head, may need work):
string s = "C030.";
Regex reg = new Regex("C[0-9]{3,3}\\.");
bool isMatch = reg.IsMatch(s);
This regex should do the trick:
Regex.IsMatch(input, #"C[0-9]{3}\..*")
Check out http://www.techotopia.com/index.php/Working_with_Strings_in_C_Sharp
for a quick tutorial on (among other things) individual access of string elements, so you can test each element for your criteria.
If you think your criteria may change, using regular expressions gives you maximum flexibility (but is more runtime intensive than regular string-element evaluation). In your case, it may be overkill, IMHO.

Is there any way to retrieve a appended int value to a String in javaScript?

I am currently working on a project that dynamically displays DB content into table.
To edit the table contents i am want to use the dynamically created "string"+id value.
Is there any way to retrieve the appended int value from the whole string in javaScript?
Any suggestions would be appreciative...
Thanks!!!
If you know that the string part is only going to consist of letters or non-numeric characters, you could use a regular expression:
var str = "something123"
var id = str.replace(/^[^\d]+/i, "");
If it can consist of numbers as well, then things get complicated unless you can ensure that string always ends with a non-numeric character. In which case, you can do something like this:
var str = "something123"
var id = str.match(/\d+$/) ? str.match(/\d+$/)[0] : "";
(''+string.match(/\d+/) || '')
Explanation: match all digits in the variable string, and make a string from it (''+).
If there is no match, it would return null, but thanks to || '', it will always be a string.
You might try using the regex:
/\d+$/
to retrieve the appended number

Resources