How to apply RegEx to whole string? - android

Is regular expression matching every single string?
For example:
String s = "android4you2 and 4us";
What's the RegEx that I have to write to make "s" only for [a-z]?

Your question is unclear, to match the whole string, you could do:
if (s.matches("[a-zA-Z0-9 ]+")) { ...
If you want to only test for alphabetic characters:
if (s.matches("[a-zA-Z]+")) { ...

try using this.
String regex = "^[A-Za-z\\s]+$";

Related

How to change styles for all numbers in string in Kotlin

How to change styles for all numbers in strings (from strings.xml) to (small) and (subscript) and (color.blue)? and where put that in recyclerView adapter (all strings in Array)?
Like this:
If you are using Kotlin, use regex to replace all the numbers with HTML formatting.
var text = "This is an example of text[1] formatting."
"\\[[0-9]+\\]".toRegex().findAll(text)
.flatMap { it.groupValues }
.forEach {
val num = it.drop(1).dropLast(1)
text = text.replace(it, "<sup>[$num]</sup>")
}
Then use tvMyTextView.setText(Html.fromHtml(text))

constructing var name from string concatanation

I'm not sure I worded the question correctly.
I have a set of variables, that go like: STO1, STO2, STO3.....STO9; and I need to get the user to input the digit to store and to recall those memory addresses.
So is there a way that the 'STO' be concatenated to the digit (1...9) to get to the var name?
The var names are declared already. I just need to either store a value or retrieve it.
I know that in other languages that is indirect addressing, I think.
Thanks in advance for any input.
Ray.
If variables defined insisde the class (so they are properties) it can be done via Reflection Api.
class Example {
var sto1 = "s1"
var sto2 = "s2"
}
fun main() {
val obj = Example()
val userInput = "1"
val prop = Example::class.memberProperties.find { it.name == "sto$userInput"}
prop as KMutableProperty<*>
//get value example
println(prop.get(obj))
//set value example
prop.setter.call(obj, "new value")
println(prop.get(obj))
}
In order to compile it you should add kotlin-reflect lib to your maven/gradle project.

Regex matches always returns false

I'm trying to validate user input so that the only allowed characters in a string are A-Z, a-z, _, - and whitespace. To do that I wrote the following code:
val regex = Regex("[\\w\\s-]")
val flag = regex.matches("Hello Overlay")
But the value of flag is false and I can't figure out why.
To match the whole string meeting a pattern use
val regex = Regex("[\\w\\s-]+")
Or, to avoid overescaping:
val regex = Regex("""[\w\s-]+""")
See the Kotlin demo. Note that matches requires a full string match, but [\w\s-] only matches a single character.
val regex = Regex("""[\w\s-]+""")
val flag = regex.matches("Hello Overlay")
println(flag) // => true
val regex = Regex("""[\w\s-]+""")
val flag = regex.matches("Hello Overlay")
println(flag) // => true

Kotlin equivalent of Java's equalsIgnoreCase

What is the equivalent of Java equalsIgnoreCase in Kotlin to compare String values?
I have used equals but it's not case insensitive.
You can use equals but specify ignoreCase parameter:
"example".equals("EXAMPLE", ignoreCase = true)
As per the Kotlin Documentation :
fun String?.equals(
other: String?,
ignoreCase: Boolean = false
): Boolean
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/equals.html
For Example:
val name: String = "Hitesh"
when{
name.equals("HITESH", true) -> {
// DO SOMETHING
}
}
#hluhovskyi's answer is correct, however to use it on EditText or TextView, use following -
etPassword.text.toString().equals(etConfirmPassword.text.toString(), ignoreCase = true)
In my case,
string1.contains(string2, ignoreCase = true)
This worked for me.
Becase I'm using like a search function here.
Normally, you don't need to find alternatives since Kotlin reuses existing Java types like String. Actually, these types are mapped to Kotlin internal types. In the case of String it looks like this:
java.lang.String -> kotlin.String
Therefore, the desired method equalsIgnoreCase would only be available if it was also provided in kotlin.String, which isn’t. The Kotlin designers decided to provide a more generic equals function that let's you specify the case insensitivity with a boolean parameter.
You can use the Java String class at any time if that's really necessary (it's not recommended, IntelliJ will complain about this):
("hello" as java.lang.String).equalsIgnoreCase("Hello")
With the help of an extension function, we could even add the functionality to the kotlin.String class:
fun String.equalsIgnoreCase(other: String) =
(this as java.lang.String).equalsIgnoreCase(other)
You could make an extension method:
/**
* Shortcut to compare strings while ignoring case
*/
fun String.similarTo(aString: String): Boolean {
return equals(aString,true)
}
Usage:
val upperCase = "ϴẞ"
val lowerCase = "θß"
if (upperCase.similarTo(lowerCase)) {
// Do your thing…
}

How to convert char to ascii value in kotlin language

I am developing an android application with kotlin in which I need to convert an string character to its ASCII value,
fun tryDiCript(cypher: String) :String {
var cypher = "fs2543i435u#$#g###sagb#!#12416###"
var originalText = ""
var regEx =Regex("[a-z]")
for(char in regEx.findAll(cypher))
{
originalText += (char.value.toInt()).toString()
}
return originalText
}
this tutorial website showed me to use char.toInt() but it gives runtime error saying
Caused by: java.lang.NumberFormatException: Invalid int: "u"
so how if anyone knows hot to convert char to ASCII value please help me.
char.value is a String. When you call String.toInt(), it is expecting a numeric string such as "1", "-123" to be parsed to Int. So, "f".toInt() will give you NumberFormatException since "f" isn't a numeric string.
If you are sure about char.value is a String containing exactly one character only. To get the ascii value of it, you can use:
char.value.first().code
Since Kotlin 1.5
if your variable is of type char for example 'a' you can simply use a.code.
The old methods (e.g. toByte()) are deprecated now.
You said ascii, not unicode. So it's easy.
This is an example that shows you how to convert a char ('A') to it's ascii value.
fun main(vararg args: String) {
println('A'.toByte().toInt())
}
The output is what we expected, 65.
Note this doesn't work with unicode.
Edit 1
I guess this to work.
fun tryDiCript(cypher: String): String {
var cypher = "fs2543i435u#$#g###sagb#!#12416###"
var originalText = ""
var regEx = Regex("[a-z]")
for(char in regEx.findAll(cypher))
originalText += char.value[0].toInt().toString()
return originalText
}
And I recommend you to use StringBuilder.
fun tryDiCript(cypher: String): String {
var cypher = "fs2543i435u#$#g###sagb#!#12416###"
val originalText = StringBuilder()
var regEx = Regex("[a-z]")
for(char in regEx.findAll(cypher))
originalText.append(char.value[0].toInt())
return originalText.toString()
}
I checked #ice1000's answer, I found the block below does not work.
fun main(vararg args: String) {
println('A'.toByte().toInt())
}
As we can see in the Kotlin Documentation String - Kotlin Programming Language,the toByte() function of String "Parses the string as a signed Byte number and returns the result." If the the content of the string is not a number, it will throw a java.lang.NumberFormatException.
But there is another function of String called toByteArray(),this function does no require the content of the string being numbers. My code is as following:
String tempString = "Hello"
val tempArray = tempString.toByteArray()
for (i in tempArray){
println(i.toInt())
}
Attention that toByteArray() function's definition in kotlin's documentaion:
fun String.toByteArray(
charset: Charset = Charsets.UTF_8
): ByteArray
The default charset is UTF-8, if you would like to use other charset, you can modify it with the parameter.

Categories

Resources