How to create regex pattern for validating editext in android? - java

am create reg-ex for validating edit text field.am not able to validate correctly.
my condition to validate is
Example (h2/g2)
At-least have a one numerical value
slash also allowed but only one,after the "/" must have one numerical value.
alphabets also allowed
How to create reg-ex for this condition.Can any one know please help me to solve this problem

Seems like you want something like this: (\w*/)?\w*\d\w*
Remember that in Java you have to duplicate backslashes \\.
Adding more examples of valid and invalid texts would help.
Edit:
Answering you comment. Yes, it does:
String value = "h2/g2";
Pattern p = Pattern.compile("(\\w*/)?\\w*\\d\\w*");
Matcher m = p.matcher(value);
Log.i("tag", "matches? " + m.matches());
prints:
I/tag(12642): matches? true

Related

Java remove dynamic substring from string

I need to remove dynamic substring from string. There is a few similar topic of this theme, but noone of them helped me. I have a string e.g.:
product test1="001" test2="abc" test3="123xzy"
and i need output:
product test1="001" test3="123xzy"
I mean I need remove test2="abc". test2 is an unique element and can be placed anywhere in original string. "abc" is dynamic variable and can have various length. What is the fastest and the most elegant solution of this problem? Thx
You can use a regular expression:
String input = "product test1=\"001\" test2=\"abc\" test3=\"123xzy\"";
String result = input.replaceAll("test2=\".*?\"\\s+", "");
In substance: find a substring like test2="xxxxxx", optionally followed by some spaces (\\s+) and replace it with nothing.

replace char in specific pattern or after specific character

The task at hand is to replace "-" with "/" in a birthday format e.g. 03-12-89 -> 03/12/89. However, the "-" must be able to appear elsewhere in the string e.g. "My-birthday-is-on-the: 03/12/89".
I have tried creating substrings, replace the "-" in the birthday part and then combine the strings again. However, that solution is inflexible and fails the testcases.
I'm thinking I must be able to do this with a regular expression, although I seem unable to construct it. So now I'm back to: String newStr = input.replace("-", "/"); Which remove all instances of "-" which I don't want.
Can anyone help?
You can use the following regex:
(?<=\d{2})-
with replacement \/ (no need to escape it in Java)
INPUT:
My-birthday-is-on-the: 03-12-89
OUTPUT:
My-birthday-is-on-the: 03/12/89
demo
Code:
String input = "My-birthday-is-on-the: 03-12-89";
System.out.println(input.replaceAll("(?<=\\d{2})-", "/"));
OUTPUT:
My-birthday-is-on-the: 03/12/89
The easiest way which comes to mind is just match \d{2}-\d{2}-\d{2}, with capture groups. Then, use those captured numbers to rebuild the birthdate the way you want it. Something like this:
String input = "My-birthday-is-on-the: 03/12/89";
input = input.replaceAll("\\b(\\d{2})-(\\d{2})-(\\d{2})\\b", "$1/$2/$3");
Demo
The advantage of specifying the full pattern is that it avoids the chance of matching anything other than a 6 digit dash-separated birthday.
Edit:
Based on your comment below, it sounds like maybe you want to do this replacement on a two dash separated number, with any number of digits. In this case, we can slightly modify the above code to the following:
String input = "Your policy number is: 123-45-6789.";
input = input.replaceAll("\\b(\\d+)-(\\d+)-(\\d+)\\b", "$1/$2/$3");

Regex to match numeric values within parentheses

I am trying to create a regex to match the each of the numeric values within parentheses.
Here is a link to a regex101 which I have been using for testing.
For instance with a String:
At present there are no approved therapies to directly target NRAS activating mutations. However, N-Ras activation may predict sensitivity to inhibitors of the Raf/MEK/ERK, PI3K/Akt, and other downstream pathways (23274911, 22392911, 21993244). The MEK inhibitors trametinib and cobimetinib (in combination with vemurafenib) have been FDA-approved for BRAF V600E- and V600K-mutant melanoma, and are currently being studied in clinical trials in solid tumors and hematologic malignancies (22663011, 25265494). Several preclinical studies have suggested that combinations of MEK inhibitors with inhibitors of other downstream molecules, such as PI3K, eIF4A, and Plk1, result in synergistic growth inhibition in NRAS-mutant melanoma in vitro and in vivo (19492075).
I would like to match each of the values shown in bold. I am currently using the following
Pattern citationPattern = Pattern.compile("(.?\()(\\d+)");
Matcher match = citationPattern.matcher(treatmentApproach);
and am able to get up to match each of first values within the parentheses. How can I extend it for the cases where there are more than one value within the parentheses. For example (22663011, 25265494). Thanks for your help!
I would just pull the matches from between the literal ( and ). Something like,
Pattern citationPattern = Pattern.compile("\\((.*?)\\)");
Matcher match = citationPattern.matcher(treatmentApproach);
while (match.find()) {
System.out.println(match.group());
}
I would use a pattern like this: [\(|, ](\d+)[, \)]
See it in action here: https://regex101.com/r/hoggh0/1
This finds any number between [open brackets or ", "] and [close brackets or ", "]
The only way this would fall over is if you had numbers in the text that are between comments but not between brackets and wanted to exclude them. This would include them.
"(\([0-9]+([, ]*[0-9])*\))" might be what you need. At least it's working here: https://regex101.com/r/tkQP8z/5.

How to retrieve portion of number that's within parenthesis in Java?

For part of my Java assignment I'm required to select all records that have a certain area code. I have custom objects within an ArrayList, like ArrayList<Foo>.
Each object has a String phoneNumber variable. They are formatted like "(555) 555-5555"
My goal is to search through each custom object in the ArrayList<Foo> (call it listOfFoos) and place the objects with area code "616" in a temporaryListOfFoos ArrayList<Foo>.
I have looked into tokenizers, but was unable to get the syntax correct. I feel like what I need to do is similar to this post, but since I'm only trying to retrieve the first 3 digits (and I don't care about the remaining 7), this really didn't give me exactly what I was looking for. Ignore parentheses with string tokenizer?
What I did as a temporary work-around, was...
for (int i = 0; i<listOfFoos.size();i++){
if (listOfFoos.get(i).getPhoneNumber().contains("616")){
tempListOfFoos.add(listOfFoos.get(i));
}
}
This worked for our current dataset, however, if there was a 616 anywhere else in the phone numbers [like "(555) 616-5555"] it obviously wouldn't work properly.
If anyone could give me advice on how to retrieve only the first 3 digits, while ignoring the parentheses, I would greatly appreciate it.
You have two options:
Use value.startsWith("(616)") or,
Use regular expressions with this pattern "^\(616\).*"
The first option will be a lot quicker.
areaCode = number.substring(number.indexOf('(') + 1, number.indexOf(')')).trim() should do the job for you, given the formatting of phone numbers you have.
Or if you don't have any extraneous spaces, just use areaCode = number.substring(1, 4).
I think what you need is a capturing group. Have a look at the Groups and capturing section in this document.
Once you are done matching the input with a pattern (for example "\((\\d+)\) \\d+-\\d+"), you can get the number in the parentheses using a matcher (object of java.util.regex.Matcher) with matcher.group(1).
You could use a regular expression as shown below. The pattern will ensure the entire phone number conforms to your pattern ((XXX) XXX-XXXX) plus grabs the number within the parentheses.
int areaCodeToSearch = 555;
String pattern = String.format("\\((%d)\\) \\d{3}-\\d{4}", areaCodeToSearch);
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(phoneNumber);
if (m.matches()) {
String areaCode = m.group(1);
// ...
}
Whether you choose to use a regular expression versus a simple String lookup (as mentioned in other answers) will depend on how bothered you are about the format of the entire string.

Java Regex - exclude empty tags from xml

let's say I have two xml strings:
String logToSearch = "<abc><number>123456789012</number></abc>"
String logToSearch2 = "<abc><number xsi:type=\"soapenc:string\" /></abc>"
String logToSearch3 = "<abc><number /></abc>";
I need a pattern which finds the number tag if the tag contains value, i.e. the match should be found only in the logToSearch.
I'm not saying i'm looking for the number itself, but rather that the matcher.find method should return true only for the first string.
For now i have this:
Pattern pattern = Pattern.compile("<(" + pattrenString + ").*?>",
Pattern.CASE_INSENSITIVE);
where the patternString is simply "number". I tried to add "<(" + pattrenString + ")[^/>].*?> but it didn't work because in [^/>] each character is treated separately.
Thanks
This is absolutely the wrong way to parse XML. In fact, if you need more than just the basic example given here, there's provably no way to solve the more complex cases with regex.
Use an easy XML parser, like XOM. Now, using xpath, query for the elements and filter those without data. I can only imagine that this question is a precursor to future headaches unless you modify your approach right now.
So a search for "<number[^/>]*>" would find the opening tag. If you want to be sure it isn't empty, try "<number[^/>]*>[^<]" or "<number[^/>]*>[0-9]"

Categories