Using string.all with regex - android

I am trying to check if a string has all the forbidden characters like "/#$%^&" ...
i tried to find a solution but couldn't find anything , i just want to check if all characters in the string match regex pattern \w
string.all seems perfect but i cant add regex pattern to it
here is what i am trying to do:
// "abce#ios" must return false because it contains #
// "abcdefg123" must return true
fun checkForChars(string :String) :Boolean {
val pattern = "\\w".toRegex()
return (string.contains(regex = pattern))
}
thanks in advance

You don't need to use regex at all with all:
fun checkForChars(string: String): Boolean = string.all(Char::isLetterOrDigit)

You made several mistakes:
\w pattern matches exactly one letter, if you want to match zero or more letters you need to change it to: \w*
Instead of checking whether the string contains the regex, you need to check if it matches the regex.
The final solution is the following:
fun checkForChars(string :String) :Boolean {
val pattern = "\\w*".toRegex()
return (string.matches(pattern))
}

You can use
Regex("[^/#$%^&]*").matches(string) to check for the forbidden characters.
You can include any forbidden characters into a [^...]* construction. Though a " character would need to be screened and a \ character would need to be screened twice. Regex("[^\\\\/#$%^&\"]*").
For \\w* regex you can use Regex("\\w*").matches(string)

Related

Kotlin regex not working for polish char ("ł") which I get at runtime

I've declared a regex like this:
"(^\\d{1,}\\,\\d{2}|^0) zł$"
Unfortunately it doesn't match below value (but it should)
508,00 zł
NOTE1: I've discovered, that the problem is probably with the ł character
NOTE2: The problem is, that i am getting this String from an API and check it at runtime (it has exact value as I described)
NOTE3: I've also tried to manually match my pattern in the debugger evaluation (when I just typed the "508, 00zł" by hand) and it matched. Unfortunately the string itself that I get doesn't match at runtime. What can be the possible problem?
Code:
val value = getFromApi() // 508,00 zł
val regex = "(^\\d{1,}\\,\\d{2}|^0) zł$".toRegex()
regex.matches(value) // returns false
The letter ł is not a culprit here since there is one Unicode representation for it.
The most common issue is the whitespace: it can be any Unicode whitespace there and from the looks of it, you will never be able to tell.
To match any ASCII whitespace, you may use \s. Here, you had this kind of whitespace, so my top comment below the question worked for you.
To match any Unicode whitespace, you may use \p{Z} to match any one whitespace character, or \p{Z}* to match 0 or more of their occurrences:
val value = "508,00 zł"
val regex = """^(\d+,\d{2}|0)\p{Z}zł$""".toRegex()
// val regex = """^(\d+,\d{2}|0)\p{Z}*zł$""".toRegex()
println(regex.matches(value)) // => True
See Kotlin demo
Also, note the use of the raw string literals (delimited with triple double quotation marks), they enable the use of a single backslash as the regex escape char.
Note {1,} is the same as + quantifier that matches 1 or more repetitions.

Create regex pattern for a specified String

I want to check if a String has a specified structure. I think regex would be the best way to test the String, but I have never used regex before and have sadly no clue how it works. I watched some explanations on stackoverflow, but I couldn't find a good explanation how the regex pattern was created.
My String gets returned from a DataMatrix scanner. For example
String contained = "~ak4,0000D"
Now I want to test this String, if it matches the pattern from the regex.
The String starts everytime with the "~".
After this, two lower cased charactes follow in this example "ak".
After this, there follows a six character long value "4,0000". Main problem here, because the comma can sit anywhere in this value, but the comma must be contained in it. For example it can be ",16000" or "150,00" or "2,8000".
At the last position there must be one of this characters A B C D E F G H J K L M in uppercase contained.
I hope some of you guys can help me.
The regex would be ~[a-z]{2}(?=[\d\,]{6})((\d)*\,(\d)*)[A-H|J-M]{1}$ You can create and test expressions here
boolean isMatch(String STRING_YOU_WANT_TO_MATCH)
{
Pattern patt = Pattern.compile(YOUR_REGEX_PATTERN);
Matcher matcher = patt.matcher(STRING_YOU_WANT_TO_MATCH);
return matcher.matches();
}
You need to use a positive lookahead based regex like below.
System.out.println("~ak4,0000D".matches("~[a-z]{2}(?=\\d*,\\d*.$)[\\d,]{6}[A-HJ-M]"));
System.out.println("~fk,10000D".matches("~[a-z]{2}(?=\\d*,\\d*.$)[\\d,]{6}[A-HJ-M]"));
System.out.println("~jk400,00D".matches("~[a-z]{2}(?=\\d*,\\d*.$)[\\d,]{6}[A-HJ-M]"));
System.out.println("~ak4,0000D".matches("~[a-z]{2}(?=\\d*,\\d*.$)[\\d,]{6}[A-HJ-M]"));
System.out.println("~fk10000,D".matches("~[a-z]{2}(?=\\d*,\\d*.$)[\\d,]{6}[A-HJ-M]"));
System.out.println("~jk400,00I".matches("~[a-z]{2}(?=\\d*,\\d*.$)[\\d,]{6}[A-HJ-M]"));
System.out.println("~ak40000,Z".matches("~[a-z]{2}(?=\\d*,\\d*.$)[\\d,]{6}[A-HJ-M]"));
System.out.println("~fky,10000D".matches("~[a-z]{2}(?=\\d*,\\d*.$)[\\d,]{6}[A-HJ-M]"));
System.out.println("~,jk40000D".matches("~[a-z]{2}(?=\\d*,\\d*.$)[\\d,]{6}[A-HJ-M]"));
Output:
true
true
true
true
true
false
false
false
false
One thing you need to know about regular expressions are that they are a family of things, not one specific thing. There are rather a lot of distinct but similar regular expression languages, and the facilities supporting them vary from programming language to programming language.
Here is a regex pattern that will work in most regex languages to match your strings:
"^~[a-z][a-z]((,[0-9][0-9][0-9][0-9][0-9])|([0-9],[0-9][0-9][0-9][0-9])|([0-9][0-9],[0-9][0-9][0-9])|([0-9][0-9][0-9],[0-9][0-9])|([0-9][0-9][0-9][0-9],[0-9])|([0-9][0-9][0-9][0-9][0-9],))[A-HJ-M]$"
The '^' anchors the pattern to the beginning of the string, and the '$' anchors it to the end, so that the pattern must match the whole string as opposed to a substring. Characters enclosed in square brackets represent "character classes" matching exactly one character from among a set, with the two characters separated by a '-' representing a range of characters. The '|' separates alternatives, and parentheses serve to group subpatterns. For some regex engines, the parentheses and '\' symbols need to be escaped via a preceeding '\' character to have these special meanings instead of representing themselves.
A more featureful regex language can allow that to be greatly simplified; for example:
"^~[a-z]{2}[0-9,]{6}(?<=[a-z][0-9]*,[0-9]*)[A-HJ-M]$"
The quantifiers "{2}" and "{6}" designate that the preceding subpattern must match exactly the specified number of times (instead of once), and the quantifier "*" designates that the preceding subpattern may match any number of times, including zero. Additionally, the "(?<= ...)" is a zero-length look-behind assertion, which tests whether the previous characters of the input match the given sub-pattern (in addition to having already matched the preceding sub-pattern); the characters must also match the subsequent sub-pattern (which does consume them). The '.' metacharacter and '*' quantifier are supported in pretty much all regex languages, but assertions and curly-brace quantifiers are less widely supported. Java's and Perl's regular expression languages will both understand this pattern, however.
~[a-z]{2}[\d|\,]{6}[A-M]
I'm no pro at regex though,but I used this site everytime to build my pattern:
RegExr
Use it like this in your code:
Pattern pattern = Pattern.compile(yourPatternAsAString);
Matcher matcher = pattern.matcher(yourInputToMatch);
if(matcher.matches()) {
// gogogo
}

PatternSyntaxException: String.replaceAll() android

I want to remove all { } as follow:
String regex = getData.replaceAll("{", "").replaceAll("}", "");
but force close my app with log.
java.util.regex.PatternSyntaxException: Syntax error U_REGEX_RULE_SYNTAX
what have i done wrong ?
You need to escape {:
String regex = getData.replaceAll("\\{", "").replaceAll("\\}", "");
Curly brackets are used to specify repetition in regex's, therefore you will have to escape them.
Furthermore, you should also consider removing all the brackets in one go, instead of called replaceAll(String, String) twice.
String regex = getData.replaceAll("\\{|\\}", "");
For what you want to do you don't need to use a regex!
You can make use of the replace method instead to match specific chars, which increases readability a bit:
String regex = getData.replace("{", "").replace("}", "");
Escaping the \\{ just to be able to use replaceAll works, but doesn't make sense in your case

How to use regex in android

I need help to match a string with a regex. An example of the string is
"Longitude: 34.847368\nLatitude: 30.435345\nAltitiude: 130.34554"
So in this string, the numbers can change, and its possible there is no decimal value.
When I try this code,
Pattern pattern = Pattern.compile("Longitude: -?\\d+(\\.\\d+)?\nLatitude: -?\\d+(\\.\\d+)?\nAltitude: -?\\d+(\\.\\d+)?");
I get an error saying \. is an invalid escape sequence, can any one help?
You have to use a double slash, otherwise Java sees it as a String escape sequence, not a Regex escape sequence. Try this:
Pattern pattern = Pattern.compile("Longitude: \\d+(\\.\\d+)?\nLatitude: \\d+(\\.\\d+)?\nAltitude: \\d+(\\.\\d+)?");
Soxxeh and aroth are almost definitly right, but in future, maybe this will help:
http://gskinner.com/RegExr/
I use it all the time :D

Android: are there any good solutions how to validate Editboxes

For example, I want to Validate Minimum-Length, and if it's Email, a PhoneNumber.
How is this possible in android. I want to validate.
If you wan to prevent user to type something, then extend the InputFilter and register it with your EditText.
// built in InputFilter.LengthFilter limits the umber of chars
EditText.setFilters(new Filter[]{new InputFilter.LengthFilter(100)})
There are a number of things that you can do to validate
Add input filters. More on it is here http://developer.android.com/reference/android/text/InputFilter.html How to add filter to editable view is mentioned here http://developer.android.com/reference/android/text/Editable.html#setFilters%28android.text.InputFilter
Use TextWatchers to modify the content on the go. More on TextWatchers is here http://developer.android.com/reference/android/text/TextWatcher.html Set this up for your EditText using http://developer.android.com/reference/android/widget/TextView.html#addTextChangedListener(android.text.TextWatcher)
Note: There are few of them implemented in Android itself. Make use of them if you can. Look for subclasses in the documentation for TextWatcher and InputFilter
For the validation of Text box
1. minimum length: u can directly give the length of that text.
2. mail validation:
public boolean isEmailValid(String email)
{
String regExpn =
"^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))#"
+"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+"[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
+"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+"[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+"([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";
CharSequence inputStr = email;
pattern = Pattern.compile(regExpn,Pattern.CASE_INSENSITIVE);
matcher = pattern.matcher(inputStr);
if(matcher.matches())
return true;
else
return false;
}
1. For phone number: If you want to fix length then give the length and the input type is number.
Also take a look here :) Android: Validate an email address (and more) in EditText

Categories

Resources