I am wanting to create a regex for the following number formats:
+XXXXXXXXXX. +1(XXX)xxxxxx, +x(xxx)-xxx-xxxx, xxx-xxx-xxxx, xxx-xxxx, and Phone Number:,Phone:,Tel: with all the above formats. All with the output of xxxxxxxxxx
Below is a snippet of my code.
public static String getPhoneNumber() // returns the phone number formatted as a sequence of digits
{
String regex = "^\\(?([0-9]{3})\\)?[-.\\s]?([0-9]{3})[-.\\s]?([0-9]{4})(?:Tel:)$";
Pattern pattern = Pattern.compile(regex);
for (int i = 0; i < line.length(); i++)
{
//if phone number format includes -, . , spaces, + sign in front
if (line.matches("[+]?\\d?[- .]?(\\([0-9]\\d{2}\\)|[0-9]\\d{2})[- .]?\\d{3}[- .]?\\d{4}$")) {
phoneNumber = line.replaceAll("[^\\d.]", "").replace("-", "").replace(".", "").replace(" ", "").replace("(", "").replace(")", "")
.replace("+", "");
}
else
{
getEmailAddress();
}
}
//System.out.println(phoneNumber);
return phoneNumber;
}
Try regex ^(?:(?:Tel|Phone Number|Phone): )?(\+?\(?\d{3}\)?[-. ]\d{3}[-. ]\d{4})$.
This will match the phone numbers with the keywords Phone,Tel or Phone Number and not with others.
Capture group $1 to get the phone number.
Regex
It seems you want to remove all non-digits, so just do that. To select lines, match those that have (at least) 10 digits:
if (line.matches("(\\D*\\d){10}.*"))) {
phoneNumber = line.replaceAll("\\D", "");
}
is all you need.
String pattern = "\d{10}|(?:\d{3}-){2}\d{4}|\(\d{3}\)\d{3}-?\d{4}";
Related
I am trying to read otp number from given String i have applied this below string but i am getting two number can any one please help me how to get otp number
String str="Your OTP for Darshann is : 9999%n 12341234123";
String numberOnly= str.replaceAll("[^0-9]", "");
I want to read number just after Your OTP for Darshann is : this text which is 9999 i
By replacing with empty string "" you are concatenating the numbers. This is why have incorrect results.
Try this instead:
String str="Your OTP for Darshann is : 9999%n 12341234123";
String numberOnly= str.replaceAll("[^0-9]", " ");
List<String> numbers = Arrays.asList(numberOnly.trim().split(" ")).stream()
.filter(s->!s.isBlank())
.collect(Collectors.toList());
System.out.println(numbers);
This would give a list of all numbers found in the text:
[9999, 12341234123]
Of course if there is more than one number in the string this function will produce more than one result.
String message = "Your OTP for Darshann is 1234";
// split the message by "is"
String[] parts = message.split("is ");
String OTP = parts[1];
// rgx
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(OTP);
if (matcher.find()) {
String OTPnumber = matcher.group();
System.out.print("OTP is: " + OTPnumber);
} else {
System.out.println("not found");
}
I have a String message with 6 digit OTP. but it is not in the beginning or in the end. So indexing couldn't help. and replace is working but my message may changed any time so this trick also failed.
My message example :
Your OTP code is : 123456
FA+9qCX9VSu
String subFirst= message.replace("<#> Your OTP code is : ", "");
String finalOTP = message.replace("FA+9qCX9VSu", "");
it produce the expected result for only this static message.
How to get only 6 digit number for any message. or is there any other way to extract OTP from message ?
you can get otp like this.
String allNum=message.replaceAll("[^0-9]","");
String otp=allNum.substring(0,6);
You can extract any 6 digit number from any String message.
"|" is used to lookup more possible combinations. Only "\d{6}" also give you the correct result for your problem.
//find any 6 digit number
Pattern mPattern = Pattern.compile("(|^)\\d{6}");
if(message!=null) {
Matcher mMatcher = mPattern.matcher(message);
if(mMatcher.find()) {
String otp = mMatcher.group(0);
Log.i(TAG,"Final OTP: "+ otp);
}else {
//something went wrong
Log.e(TAG,"Failed to extract the OTP!! ");
}
}
you can use regex to find the number substring and the just take the 6 first from the substring, you can find how to use regex here :
https://en.wikipedia.org/wiki/Regular_expression
if your message is always start with "Your OTP code is : " and have break line (\n)
after codes use this:
Pattern pattern = Pattern.compile("is : (.*?)\\n", Pattern.DOTALL);
Matcher matcher = pattern.matcher(message);
while (matcher.find()) {
Log.i("tag" , matcher.group(1));
}
Try this hope this will help you.
String expression = "[0-9]{6}";
CharSequence inputStr = message;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
Try this:
msg = 'Your OTP code is : 123456'
otp = msg.split()[-1]
Use a regex like this:
public static void main(final String[] args) {
String input = "Your OTP code is : 123456\r\n" + "\r\n" + "FA+9qCX9VSu";
Pattern regex = Pattern.compile(":\\s([0-9]{6})");
Matcher m = regex.matcher(input);
if (m.find()) {
System.out.println(m.group(1));
}
}
String message="The OTP is 145673 and the same is active for next 20 mins";
System.out.println(message.replaceFirst("\d{6}", "******"));
I hope this helps.
someone can help me with code?
How to search word in String text, this word end "." or "," in java
I don't want search like this to find it
String word = "test.";
String wordSerch = "I trying to tasting the Artestem test.";
String word1 = "test,"; // here with ","
String word2 = "test."; // here with "."
String word3 = "test"; //here without
//after i make string array and etc...
if((wordSearch.equalsIgnoreCase(word1))||
(wordSearch.equalsIgnoreCase(word2))||
(wordSearh.equalsIgnoreCase(word3))) {
}
if (wordSearch.contains(gramer))
//it's not working because the word Artestem will contain test too, and I don't need it
You can use the matches(Regex) function with a String
String word = "test.";
boolean check = false;
if (word.matches("\w*[\.,\,]") {
check = true;
}
You can use regex for this
Matcher matcher = Pattern.compile("\\btest\\b").matcher(wordSearch);
if (matcher.find()) {
}
\\b\\b will match only a word. So "Artestem" will not match in this case.
matcher.find() will return true if there is a word test in your sentence and false otherwise.
String stringToSearch = "I trying to tasting the Artestem test. test,";
Pattern p1 = Pattern.compile("test[.,]");
Matcher m = p1.matcher(stringToSearch);
while (m.find())
{
System.out.println(m.group());
}
You can transform your String in an Array divided by words(with "split"), and search on that array , checking the last character of the words(charAt) with the character that you want to find.
String stringtoSearch = "This is a test.";
String whatIwantToFind = ",";
String[] words = stringtoSearch.split("\\s+");
for (String word : words) {
if (whatIwantToFind.equalsignorecas(word.charAt(word.length()-1);)) {
System.out.println("FIND");
}
}
What is a word? E.g.:
Is '5' a word?
Is '漢語' a word, or two words?
Is 'New York' a word, or two words?
Is 'Kraftfahrzeughaftpflichtversicherung' (meaning "automobile liability insurance") a word, or 3 words?
For some languages you can use Pattern.compile("[^\\p{Alnum}\u0301-]+") for split words. Use Pattern#split for this.
I think, you can find word by this pattern:
String notWord = "[^\\p{Alnum}\u0301-]{0,}";
Pattern.compile(notWord + "test" + notWord)`
See also: https://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
How to edit this string and split it into two?
String asd = {RepositoryName: CodeCommitTest,RepositoryId: 425f5fc5-18d8-4ae5-b1a8-55eb9cf72bef};
I want to make two strings.
String reponame;
String RepoID;
reponame should be CodeCommitTest
repoID should be 425f5fc5-18d8-4ae5-b1a8-55eb9cf72bef
Can someone help me get it? Thanks
Here is Java code using a regular expression in case you can't use a JSON parsing library (which is what you probably should be using):
String pattern = "^\\{RepositoryName:\\s(.*?),RepositoryId:\\s(.*?)\\}$";
String asd = "{RepositoryName: CodeCommitTest,RepositoryId: 425f5fc5-18d8-4ae5-b1a8-55eb9cf72bef}";
String reponame = "";
String repoID = "";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(asd);
if (m.find()) {
reponame = m.group(1);
repoID = m.group(2);
System.out.println("Found reponame: " + reponame + " with repoID: " + repoID);
} else {
System.out.println("NO MATCH");
}
This code has been tested in IntelliJ and runs without error.
Output:
Found reponame: CodeCommitTest with repoID: 425f5fc5-18d8-4ae5-b1a8-55eb9cf72bef
Assuming there aren't quote marks in the input, and that the repository name and ID consist of letters, numbers, and dashes, then this should work to get the repository name:
Pattern repoNamePattern = Pattern.compile("RepositoryName: *([A-Za-z0-9\\-]+)");
Matcher matcher = repoNamePattern.matcher(asd);
if (matcher.find()) {
reponame = matcher.group(1);
}
and you can do something similar to get the ID. The above code just looks for RepositoryName:, possibly followed by spaces, followed by one or more letters, digits, or hyphen characters; then the group(1) method extracts the name, since it's the first (and only) group enclosed in () in the pattern.
I have zipcodes that are 5 digits, and I have zipcodes that are 9 digits with a dash in between.
The problem is that the 5 digit zip codes have a dash at the end, and I would like to remove the dash only if the zipcodes aren't 9 digit zipcodes.
Additional clarification: So I have zipcodes in the following formats: #####- and #####-####. I'd like to change it to ##### and #####-####
if(zipCode.endsWith("-")) {
// remove '-'
}
if (postcode.length() == 6)
postcode = postcode.substring(0,5);
You could use this regex:
(?<=^[0-9]{5})(-)(?=$)
working regex example:
http://regex101.com/r/oO1hG2
java code:
str = str.replaceAll("(?<=^[0-9]{5})(-)(?=$)", "");
Pattern p1 = Pattern.compile("(\\d{5})-?");
Pattern p2 = Pattern.compile("(\\d{4})-?(\\d{5})");
Matcher matcher = p1.matcher(zipCode);
String parsed;
if (matcher.find()) {
parsed = matcher.group(1);
} else {
matcher = p2.matcher(zipCode);
if (matcher.find()) {
parsed = matcher.group(1) + matcher.group(2);
}
}
What I would do is this:
if(zipcode.matches("\\d{5}-") //if zipcode is five digits (\d{5}) followed by a hyphen (-)...
{
zipcode = zipcode.substring(0, zipcode.length() - 1); //...make zipcode equal itself minus the last character
}
^([0-9]{5})\-$
As example (regex example), matches for 09090- will be:
0: [0,6] 09090-
1: [0,5] 09090
you can just replace it with matches
/^([0-9]{5})[\-][0-9]{4}$/ //skip replacement.