The regex
.*([0-9]{3}\\.[0-9]{2}).*
finds one match in "some short sentence 111.01 ", but it failed to match the first occurrence "111.01" in "some short sentence 111.01 & 222.02 "
I tried the lazy quantifier .*([0-9]{3}\\.[0-9]{2})?.* or .*([0-9]{3}\\.[0-9]{2}).*? for no avail.
Please help, I need to get both occurrences, here is my code.
Thank you
Pattern myPattern = Pattern.compile(".*([0-9]{3}\\.[0-9]{2}).*");
Matcher m = myPattern.matcher(mystring);
while (m.find()) {
String found = m.group(1);
}
you need to remove ".*"s. Try this:
String mystring = "some short sentence 111.01 & 222.02 ";
Pattern myPattern = Pattern.compile("([0-9]{3}\\.[0-9]{2})");
Matcher m = myPattern.matcher(mystring);
while(m.find()) {
System.out.println("Found value: " + m.group(1) );
}
output:
Found value: 111.01
Found value: 222.02
The leading and trailing ".*" cause you to match the entire string in one match. All the lazy quantifier does in your case is controls you getting the first, not last, occurrence in the subject.
Related
What I'm trying to do:
if a String is
String a = "Love is rare"; Or
String a = "l o v e is rare"; Or
String a = "LO VE is rare";
Then,
I want the word "love" to be replaced by "hate" ignoring the space and case
My code:
a=a.toLowerCase().replace("love","hate").replace("\\s+","");
But the problem is that it removes all the spaces and change all the words to lower case. I just want to check if there is a word love by ignoring all the spaces and cases and if the word is there then replace it with some other word.
Please help!
Thank you.
Try it like this using an optional whitespace ? and the case insensitive flag. If you want to match zero or more whitespaces, you could use a whitespace and *
l ?o ?v ?e
String regex = "l ?o ?v ?e";
String[] lines = {"Love is rare", "l o v e is rare", "LO VE is rare"};
String subst = "hate";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
for (String line: lines) {
Matcher matcher = pattern.matcher(line);
String result = matcher.replaceAll(subst);
System.out.println(result);
}
That would give you:
hate is rare
hate is rare
hate is rare
Demo Java
Thanks for suggesting the term regex, Studied thoroughly and come up with this one line function which will replace "love" by "hate" ignoring the spaces and cases:
String a = "Lo ve is rare.";
Code:
a = a.replaceAll("(?i)l(\\s*)o(\\s*)v(\\s*)e","hate");
TextView.setText(a);
This would give:
hate is rare.
I've done a bunch of searching but I'm terrible with regex statements and my google-fu in this instance as not been strong.
Scenario:
In push notifications, we're passed a URL that contains a 9-digit content ID.
Example URL: http://www.something.com/foo/bar/Some-title-Goes-here-123456789.html (123456789 is the content ID in this scenario)
Current regex to parse the content ID:
public String getContentIdFromPathAndQueryString(String path, String queryString) {
String contentId = null;
if (StringUtils.isNonEmpty(path)) {
Pattern p = Pattern.compile("([\\d]{9})(?=.html)");
Matcher m = p.matcher(path);
if (m.find()) {
contentId = m.group();
} else if (StringUtils.isNonEmpty(queryString)) {
p = Pattern.compile("(?:contentId=)([\\d]{9})(?=.html)");
m = p.matcher(queryString);
if (m.find()) {
contentId = m.group();
}
}
}
Log.d(LOG_TAG, "Content id " + (contentId == null ? "not found" : (" found - " + contentId)));
if (StringUtils.isEmpty(contentId)) {
Answers.getInstance().logCustom(new CustomEvent("eid_url")
.putCustomAttribute("contentId", "empty")
.putCustomAttribute("path", path)
.putCustomAttribute("query", queryString));
}
return contentId;
}
The problem:
This does the job but there's a specific error scenario that I need to account for.
Whoever creates the push may put in the wrong length content ID and we need to grab it regardless of that, so assume it can be any number of digits... the title can also contain digits, which is annoying. The content ID will ALWAYS be followed by ".html"
While the basic answer here would be just "replace {9} limiting quantifier matching exactly 9 occurrences with a + quantifier matching 1+ occurrences", there are two patterns that can be improved.
The unescaped dot should be escaped in the pattern to match a literal dot.
If you have no overlapping matches, no need to use a positive lookahead with a capturing group before it, just keep the capturing group and grab .group(1) value.
A non-capturing group (?:...) is still a consuming pattern, and the (?:contentId=) equals contentId= (you may remove (?: and )).
There is no need wrapping a single atom within a character class, use \\d instead of [\\d]. That [\\d] is actually a source of misunderstandings, some may think it is a grouping construct, and might try adding alternative sequences into the square brackets, while [...] matches a single char.
So, your code can look like
Pattern p = Pattern.compile("(\\d+)\\.html"); // No lookahead, + instead of {9}
Matcher m = p.matcher(path);
if (m.find()) {
contentId = m.group(1); // (1) refers to Group 1
} else if (StringUtils.isNonEmpty(queryString)) {
p = Pattern.compile("contentId=(\\d+)\\.html");
m = p.matcher(queryString);
if (m.find()) {
contentId = m.group(1);
}
}
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"));
I am trying to get substrings from the string which are between apostrophes using regex.
Format of the string: Duplicate entry 'bla#bla.bl' for key 'email'.
The regex I am using: '([^']*).
Code:
Pattern pattern = Pattern.compile("'([^']*)");
Matcher matcher = pattern.matcher(duplicated);
Log.d(TAG, matcher.group()));
I am not also sure about matcher.group(), which returns a single string, that matched the whole regex. In my case, it should return two substrings.
Can somebody correct this regex and give me an explanation?
Thanks in advance
Better to use .split() instead of Pattern Matching. Its simply hard-coding. Do as below:
String[] strSplitted = <Your String>.split("`");
Then, the strSplitted Array contains the Strings splitted between `.
I would use this regex. It is almost exactly like yours but I include the closing single quote. This is to prevent the closing single quote from being used in the next match.
'([^']*)'
And to get the contents inside the single quotes use a line similar to this:
matcher.group(1)
Here is a Java example:
Pattern regex = Pattern.compile("'([^']*)'", Pattern.MULTILINE);
Matcher matcher = regex.matcher(duplicated);
while (matcher.find()) {
Log.d(TAG, matcher.group(1)));
}
Here's my tested solution. You have to call find
Pattern pattern = Pattern.compile("'([^']*)'");
String duplicated = "Duplicate entry 'bla#bla.bl' for key 'email'";
Matcher matcher = pattern.matcher(duplicated);
String a = "";
while (matcher.find()) {
a += matcher.group(1) + "\n";
}
Result:
bla#bla.bl
email
I invent my solution like following.
int second_index = 0;
String str = "Duplicate entry 'bla#bla.bl' for key 'email'";
while (true) {
if (second_index == 0)
first_index = str.indexOf("'", second_index);
else
first_index = str.indexOf("'", second_index + 1);
if (first_index == -1)
break;
second_index = str.indexOf("'", first_index + 1);
if (second_index == -1)
break;
String temp = str.substring(first_index + 1, second_index);
Log.d("TAG",temp);
}
Output
06-25 17:25:17.689: bla#bla.bl
06-25 17:25:17.689: email