How to use regex in android - 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

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.

remove only double quotes from string before and after square bracket

I am trying to remove double quotes before square bracket like "[
and I am using following code to do it but it says illegal escape charecter.
str = str.replace("\[","[");
I want to remove only double quotes ie " which is only before square bracket ie [. Please guide me.
You can use:
str = str.replaceAll("\"\\[", "[");
Both replace() and replaceAll() do the job. Using replace, you don't have to cope with regular expressions. Don't get confused by the name. In fact replace replaces all occurrences, not just the first.
str = str.replace("\"[", "[");

Using a question mark as a String in android

Im trying to use a question mark as a variable for a string.
I've tried...
strings.xml
<string name="questionMark">\?</string>
.class
String questionMark;
questionMark = getResources().getString(R.string.questionMark);
String delim4 = (questionMark);
This causes a fource close regex error.
and
String delim4 = (\?);
This gets an error Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )
and also
I've tried putting 2 backslashes in front of it
String delim4 =(\\?)
System.out.println("delim "+ delim4);
But that just escapes the second slash and sometimes force closes as well.
the output for that was
delim \?
Can any tell me how to put in the question mark as the string. I'm using it as variable to spit a string. The String Im splitting can not be changed.
plz help
Edit added split code
if (FinishedUrl.contains(questionMark)){
String delim3 = (".com/");
String[] parts3 = FinishedUrl.split(delim3);
String JUNK3= parts3[0];
String fIdStpOne = parts3[1];
String fIdStpTwo = fIdStpOne.replaceAll("=#!/","");
String delim4 = (questionMark);
String[] parts4 = fIdStpTwo.split(delim4);
String fIdStpThree= parts3[0];
String JUNK4 = parts3[1];
FId = fIdStpThree;
}
As pointed out by user laalto, ? is a meta-character in regex. You must work around that.
Let's see what's happening here. Firstly, some ground rules:
`?` is not a special character in Java
`?` is a reserved character in regex
This entails:
String test = "?"; // Valid statement in java, but illegal when used as a regex
String test = "\?"; // Illegal use of escape character
Why is the second statement wrong? Because we are trying to escape a character that isn't special (in Java). Okay, we'll get back to this.
Now, for the split(String) method, we need to escape the ? - it being a meta-character in regex. So, we need \? for the regex.
Coming back to the string, how do we get \?? We need to escape the \(backslash) - not the question mark!
Here's the workflow:
String delim4 = "\\?";
This statement gives us \? - it escapes the \(backslash).
String[] parts4 = fIdStpTwo.split(delim4);
This lets us use \? as a regex in the split() method. Since delim4 is being passed as a regex, \? is used as ?. Here, the prefix \ is used to escape ?.
Your observations:
String delim4 = (\?);
This gets an error Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )
I covered this above. You are escaping ? at the java level - but it isn't a special character and needs no escaping - hence the error.
String delim4 =(\\?)
System.out.println("delim "+ delim4);
But that just escapes the second slash and sometimes force closes as well. the output for that was
delim \?
This is what we want. It is easier to think of this as a two stage process. The first stage deals with successfully placing a \(backslash) in front of the ?. In the second stage, regex finds that the ? has been prefixed by a \ and uses ? as a literal instead of a meta-character.
And here's how you can place the regex in your res/values/strings.xml:
<string name="questionMark">\\?</string>
By the way, there's another option - not something I use on a regular basis these days - split() works just fine.
You can use StringTokenizer which works with delimiters instead of regex. Afaik, any literal can be used as a delimiter. So, you can use ? directly:
StringTokenizer st = new StringTokenizer(stringToSplit, "?");
while (st.hasMoreTokens()) {
// Use tokens
String token = st.nextToken();
}
Easiest way is to quote or backslash them:
<string name="random">"?"</string>
<string name="random">\?</string>
The final code.
String startDelim = ("\\?");
String realDelim = (startDelim);
String[] parts4 = fIdStpOne.split(realDelim);
String fIdStpTwo= parts4[0];
String JUNK4 = parts4[1];
Normally you'd just put it literally, like
String q = "?";
However, you say you're using it to split a string. split() takes a regular expression and ? is a metacharacter in a regex. To escape it, add a backslash in front. Backslash is a special character in Java string literals so it needs to be escaped, too:
String q = "\\?";

What is the the double quotation marks in strings.xml used for?

Just a little while ago, I was looking around on GitHub, and I found there were some double quotation marks beside the string value in some strings.xml just like this:
<string name="ClipMmi" msgid="6952821216480289285">"来电显示"</string>
In short I mean this
"来电显示"
For full example please click here.
I don't know what is the "" used for? Because if I remove the "" beside the string value (e.g. "来电显示" change to 来电显示), the output won't change any more, both "来电显示" and 来电显示 will print 来电显示 as the output.
So does the quotations make any sense here?
It makes sense on languages that are using simple quotes '.
If simple quotes aren't escaped like this, \', Lint will detect an error.
Using double quotes at the start and at the end of a string value will allow you to omit these backslashes.
There may be other purposes I didn't discovered yet.

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

Categories

Resources