This question already has an answer here:
Select part of line in regular expression
(1 answer)
Closed 4 years ago.
I have this strings: https://regex101.com/r/7Er0Ch/6
I want put all my http://esupb.tabriz.ir:808x/srvSC.svc into array list.So in order to i used matcher like blow:
String regx= "#\\d+#";
Pattern pattern = Pattern.compile(regx);
Matcher matcher = pattern.matcher(url);
String[] metadata = new String[4];
while (matcher.find()) {
metadata[0] = matcher.group(1);
metadata[1] = matcher.group(2);
metadata[2] = matcher.group(3);
metadata[3] = matcher.group(4);
}
but I got not appropriate result. What is my mistake?
From requirement your regex will be
"(#\d+#)(http[^#]*svc)(#\d+#)"
group(0): (#\\d+#)(http[^#]*svc)(#\\d+#)
group(1): (#\\d+#)
group(2): (http[^#]*svc)
group(3): (#\\d+#)
Change your code to
List<String> urls = new ArrayList<>();
String url =
"#1#http://test.com:8080/srv.svc#1# " +
"#2#http://test.com:8081/srv.svc#2# " +
"#3#http://test.com:8082/srv.svc#3# " +
"#4#http://test.com:8083/srv.svc#4# " +
"#5#http://test.com:8084/srv.svc#5# ";
String regx = "(#\\d+#)(http[^#]*svc)(#\\d+#)";
Pattern pattern = Pattern.compile(regx);
Matcher matcher = pattern.matcher(url);
int from = 0;
while (matcher.find(from)) {
urls.add(matcher.group(2));
from = matcher.start() + 1;
}
You regex #\\d+#matches # followed by matching one or more times a digit and then another # .It does not use capturing groups.
For your example data you could remove that match from the string giving you the desired result leaving out matching any pattern for the string that is left. It could also match inside the string instead of only at the start and the end.
To match your example string(s) like http://esupb.tabriz.ir:808x/srvSC.svc you might use your regex to match the start and the end, and capture in a group what is in between.
^#\d+#(https?://test.ir:808\d/srvSC\.svc)#\d+#$
In Java
^#\\d+#(https?://test.ir:808\\d/srvSC\\.svc)#\\d+#$
Regex demo
Demo Java
Explanation
^ Assert the start of the string
#\d+# Match #, one or more times a digit and another #
( Start capturing group
https?://test.ir:808\d Match the start of the url with an optional s s? and a digit after 808. Use \d+ to match one or more digits.
/srvSC\.svc Match /srvSC.svc
#\d+# Match #, one or more times a digit and another #
) Close caputring group
$ Assert the end of the string
For the input text:
<p>Arbit string <b>of</b><br><br>text. <em>What</em> to <strong>do</strong> with it?
I run the following code:
Whitelist list = Whitelist.simpleText().addTags("br");
// Some other code...
// plaintext is the string shown above
retVal = Jsoup.clean(plaintext, StringUtils.EMPTY, list,
new Document.OutputSettings().prettyPrint(false));
I get the output:
Arbit string <b>of</b>
text. <em>What</em> to <strong>do</strong> with it?
I don't want Jsoup to convert the <br> tags to line breaks, I want to keep them as-is. How can I do that?
Try this:
Document doc2deal = Jsoup.parse(inputText);
doc2deal.select("br").append("br"); //or append("<br>")
This is not reproducible for me. Using Jsoup 1.8.3 and this code:
String html = "<p>Arbit string <b>of</b><br><br>text. <em>What</em> to <strong>do</strong> with it?";
String cleaned = Jsoup.clean(html,
"",
Whitelist.simpleText().addTags("br"),
new Document.OutputSettings().prettyPrint(false));
System.out.println(cleaned);
I get the following output:
Arbit string <b>of</b><br><br>text. <em>What</em> to <strong>do</strong> with it?
Your problem must be somewhere else I guess.
I am setting text using setText() by following way.
prodNameView.setText("" + name);
prodOriginalPriceView.setText("" + String.format(getString(R.string.string_product_rate_with_ruppe_sign), "" + new BigDecimal(price).setScale(2, RoundingMode.UP)));
In that First one is simple use and Second one is setting text with formatting text.
Android Studio is so much interesting, I used Menu Analyze -> Code Cleanup and i got suggestion on above two lines like.
Do not concatenate text displayed with setText. Use resource string
with placeholders. less... (Ctrl+F1)
When calling TextView#setText:
Never call Number#toString() to format numbers; it will not handle fraction separators and locale-specific digits properly. Consider
using String#format with proper format specifications (%d or %f)
instead.
Do not pass a string literal (e.g. "Hello") to display text. Hardcoded text can not be properly translated to other languages.
Consider using Android resource strings instead.
Do not build messages by concatenating text chunks. Such messages can not be properly translated.
What I can do for this? Anyone can help explain what the thing is and what should I do?
Resource has the get overloaded version of getString which takes a varargs of type Object: getString(int, java.lang.Object...). If you setup correctly your string in strings.xml, with the correct place holders, you can use this version to retrieve the formatted version of your final String. E.g.
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
using getString(R.string.welcome_message, "Test", 0);
android will return a String with
"Hello Test! you have 0 new messages"
About setText("" + name);
Your first Example, prodNameView.setText("" + name); doesn't make any sense to me. The TextView is able to handle null values. If name is null, no text will be drawn.
Don't get confused with %1$s and %2$d in the accepted answer.Here is a few extra information.
The format specifiers can be of the following syntax:
%[argument_index$]format_specifier
The optional argument_index is specified as a number ending with a “$” after the “%” and selects the specified argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc.
The required format specifier is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument's data type.
Example
We will create the following formatted string where the gray parts are inserted programmatically.
Hello Test! you have 0 new messages
Your string resource:
< string name="welcome_messages">Hello, %1$s! You have %2$d new
messages< /string >
Do the string substitution as given below:
getString(R.string.welcome_message, "Test", 0);
Note:
%1$s will be substituted by the string "Test"
%2$d will be substituted by the string "0"
I ran into the same lint error message and solved it this way.
Initially my code was:
private void displayQuantity(int quantity) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + quantity);
}
I got the following error
Do not concatenate text displayed with setText. Use resource string with placeholders.
So, I added this to strings.xml
<string name="blank">%d</string>
Which is my initial "" + a placeholder for my number(quantity).
Note: My quantity variable was previously defined and is what I wanted to append to the string. My code as a result was
private void displayQuantity(int quantity) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText(getString(R.string.blank, quantity));
}
After this, my error went away. The behavior in the app did not change and my quantity continued to display as I wanted it to now without a lint error.
Do not concatenate text inside your setText() method, Concatenate what ever you want in a String and put that String value inside your setText() method.
ex: correct way
int min = 120;
int sec = 200;
int hrs = 2;
String minutes = String.format("%02d", mins);
String seconds = String.format("%02d", secs);
String newTime = hrs+":"+minutes+":"+seconds;
text.setText(minutes);
Do not concatenate inside setText() like
text.setText(hrs+":"+String.format("%02d", mins)+":"+String.format("%02d", secs));
You should check this thread and use a placeholder like his one (not tested)
<string name="string_product_rate_with_ruppe_sign">Price : %1$d</string>
String text = String.format(getString(R.string.string_product_rate_with_ruppe_sign),new BigDecimal(price).setScale(2, RoundingMode.UP));
prodOriginalPriceView.setText(text);
Don't Mad, It's too Simple.
String firstname = firstname.getText().toString();
String result = "hi "+ firstname +" Welcome Here";
mytextview.setText(result);
the problem is because you are appending "" at the beginning of every string.
lint will scan arguments being passed to setText and will generate warnings, in your case following warning is relevant:
Do not build messages by
concatenating text chunks. Such messages can not be properly
translated.
as you are concatenating every string with "".
remove this concatenation as the arguments you are passing are already text. Also, you can use .toString() if at all required anywhere else instead of concatenating your string with ""
I fixed it by using String.format
befor :
textViewAddress.setText("Address"+address+"\n"+"nCountry"+"\n"+"City"+"city"+"\n"+"State"+"state")
after :
textViewAddress.setText(
String.format("Address:%s\nCountry:%s\nCity:%s\nState:%s", address, country, city, state));
You can use this , it works for me
title.setText(MessageFormat.format("{0} {1}", itemList.get(position).getOppName(), itemList.get(position).getBatchNum()));
If you don't need to support i18n, you can disable this lint check in Android Studio
File -> Settings -> Editor -> Inspections -> Android -> Lint -> TextView Internationalization(uncheck this)
prodNameView.setText("" + name); //this produce lint error
val nameStr="" + name;//workaround for quick warning fix require rebuild
prodNameView.setText(nameStr);
I know I am super late for answering this but I think you can store the data in a varible first then you can provide the variable name. eg:-
// Java syntax
String a = ("" + name);
String b = "" + String.format(getString(R.string.string_product_rate_with_ruppe_sign);
String c = "" + new BigDecimal(price).setScale(2, RoundingMode.UP));
prodNameView.setText(a);
prodOriginalPriceView.setText(b, c);
if it is textView you can use like that : myTextView.text = ("Hello World")
in editText you can use myTextView.setText("Hello World")
I try to get only this part "9916-4203" in "Region Code:9916-4203 " in android. How can I do this?
I tried below code, I used substring method but it doesn't work:
firstNumber = Integer.parseInt(message.substring(11, 19));
If you know that string contains "Region Code:" couldn't you do a replace?
message = message.replace("Region Code:", "");
Assumed that you have only one phone number in your String, the following will remove any non-digit characters and parse the resulting number:
public static int getNumber(String num){
String tmp = "";
for(int i=0;i<num.length();i++){
if(Character.isDigit(num.charAt(i)))
tmp += num.charAt(i);
}
return Integer.parseInt(tmp);
}
Output in your case: 99164203
And as already mentioned, you won't be able to parse any String to Integer in case there are any non-digit characters
Im going to guess that what you want to extract is the full region code text minus the title. So maybe using regex would be a good simple fit for you?
String myString = "Region Code:9916-4203";
String match = "";
String pattern = "\:(.*)";
Pattern regEx = Pattern.compile(pattern);
Matcher m = regEx.matcher(myString);
// Find instance of pattern matches
Matcher m = regEx.matcher(myString);
if (m.find()) {
match = m.group(0);
}
Variable match will contain "9916-4203"
This should work for you.
Java code sourced from http://android-elements.blogspot.in/2011/04/regular-expressions-in-android.html
In Java the substring() method works with the first parameter being inclusive and the second parameter being exclusive. Meaning "Hello".substring(0, 2); will result in the string He.
In addition to excluding the parsing of something that isn't a number like #Opiatefuchs mentioned, your substring method should instead be message.substring(12, 21).
I have text like:
לשלום קוראים לי משהmy test is עלות 39.40, כל מיני data 1.1.2015 ויש גם data 123456 מידע
This text have Hebrew and English characters, I need to eliminate all except the 6 digit number (may be 5, this num: 123456).
Can you help me with regular expression for this?
Tried:
String patternS = "[אבגדהוזחטיכךלמםנןסעפףצץקרשתa-fA-F0-9]{5,10}.*";
Pattern pattern = Pattern.compile(patternString);
With no success
To match everything except the number use:
\d+(?:[^\d]\d+)+|[\p{L}\p{M}\p{Z}\p{P}\p{S}\p{C}]+
String resultString = subjectString.replaceAll("\\d+(?:[^\\d]\\d+)+|[\\p{L}\\p{M}\\p{Z}\\p{P}\\p{S}\\p{C}]+", "");
This will give you every 6 didgit combination in your string.
(\d{6,6})
We can't give you a more detailled regex since we do now know the pattern of those strings.
In case there is always the "data " prefix you can also use this to make the pattern more accurate:
data (\d{6,6})
Try something like this:
String patternS = "(\d{5,6})";
Pattern pattern = Pattern.compile(patternS);
Matcher m = pattern.matcher(yourText);
int number = Integer.parseInt(m.group(1));
where yourText is the Hebrew/English text you want to match.
This would work for this specific example.
String s = " לשלום קוראים לי מש my test is עלות 39.40, כל מיני data 1.1.2015 ויש גם data 123456 מידע1234";
System.out.println(s.replaceAll(".*\\b(\\d{5,6})\\b.*", "$1"));