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");
}
Related
I have a very long text and I'm extracting some specific values that are followed by some particular words. Here's an example of my long text:
.........
FPS(FramesPerSecond)[ValMin: 29.0000, ValMax: 35.000]
.........
TotalFrames[ValMin: 100000, ValMax:200000]
.........
MemoryUsage(In MB)[ValMin:190000MB, ValMax:360000MB]
.........
here's my code:
File file = filePath.toFile();
JSONObject jsonObject = new JSONObject();
String FPSMin="";
String FPSMax="";
String TotalFramesMin="";
String TotalFramesMax="";
String MemUsageMin="";
String MemUsageMax="";
String log = "my//log//file";
final Matcher matcher = Pattern.compile("FPS/\(FramesPerSecond/\)/\[ValMin:");
if(matcher.find()){
FPSMin= matcher.end().trim();
}
But I can't make it work. Where am I wrong? Basically I need to select, for each String, the corresponding values (max and min) coming from that long text and store them into the variables. Like
FPSMin = 29.0000
FPSMax = 35.0000
FramesMin = 100000
Etc
Thank you
EDIT:
I tried the following code (in a test case) to see if the solution could work, but I'm experiencing issues because I can't print anything except an object. Here's the code:
#Test
public void whenReadLargeFileJava7_thenCorrect()
throws IOException, URISyntaxException {
Scanner txtScan = new Scanner("path//to//file//test.txt");
String[] FPSMin= new String[0];
String FPSMax= "";
//Read File Line By Line
while (txtScan.hasNextLine()) {
// Print the content on the console
String str = txtScan.nextLine();
Pattern FPSMin= Pattern.compile("^FPS\\(FramesPerSecond\\)\\[ValMin:");
Matcher matcher = FPSMin.matcher(str);
if(matcher.find()){
String MinMaxFPS= str.substring(matcher.end(), str.length()-1);
String[] splitted = MinMaxFPS.split(",");
FPSMin= splitted[0].split(": ");
FPSMax = splitted[1];
}
System.out.println(FPSMin);
System.out.println(FPSMax);
}
Maybe your pattern should be like this ^FPS\\(FramesPerSecond\\)\\[ValMin: . I've tried it and it works for me.
String line = "FPS(FramesPerSecond)[ValMin: 29.0000, ValMax: 35.000]";
Pattern pattern = Pattern.compile("^FPS\\(FramesPerSecond\\)\\[ValMin:");
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
System.out.println(line.substring(matcher.end(), line.length()-1));
}
}
In that way, you get the offset of the line that you want to extract data and using the substring function you can get all characters starting from offset until the size of the line-1 (because you dont want to get also the ] character)
The following regular expression will match and capture the name, min and max:
Pattern.compile("(.*)\\[.+:\\s*(\\d+(?:\\.\\d+)?)[A-Z]*,.+:\\s*(\\d+(?:\\.\\d+)?)[A-Z]*\\]");
Usage (extracting the captured groups):
String input = (".........\n" +
"FPS(FramesPerSecond)[ValMin: 29.0000, ValMax: 35.000]\n" +
".........\n" +
"TotalFrames[ValMin: 100000, ValMax:200000]\n" +
".........\n" +
"MemoryUsage(In MB)[ValMin:190000MB, ValMax:360000MB]\n" +
".........");
for (String s : input.split("\n")) {
Matcher matcher = pattern.matcher(s);
if (matcher.matches()) {
System.out.println(matcher.group(1) + ", " + matcher.group(2) + ", " + matcher.group(3));
}
}
Output:
FPS(FramesPerSecond), 29.0000, 35.000
TotalFrames, 100000, 200000
MemoryUsage(In MB), 190000, 360000
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.
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}";
I am trying to get a regex to match, then get the value with it. For example, I want to check for 1234 as an id and if present, get the status (which is 0 in this case). Basically its id:status. Here is what I am trying:
String topicStatus = "1234:0,567:1,89:2";
String someId = "1234";
String regex = "\\b"+someId+":[0-2]\\b";
if (topicStatus.matches(regex)) {
//How to get status?
}
Not only do I not know how to get the status without splitting and looping through, I don't know why it doesn't match the regex.
Any help would be appreciated. Thanks.
Use the Pattern class
String topicStatus = "1234:0,567:1,89:2";
String someId = "1234";
String regex = "\\b"+someId+":[0-2]\\b";
Pattern MY_PATTERN = Pattern.compile(regex);
Matcher m = MY_PATTERN.matcher(topicStatus);
while (m.find()) {
String s = m.group(1);
System.out.println(s);
}
The key here is to surround the position you want [0-2] in parenthesis which means it will be saved as the first group. You then access it through group(1)
I made some assumptions that your pairs we're always comma separate and then delimited by a colon. Using that I just used split.
String[] idsToCheck = topicStatus.split(",");
for(String idPair : idsToCheck)
{
String[] idPairArray = idPair.split(":");
if(idPairArray[0].equals(someId))
{
System.out.println("id : " + idPairArray[0]);
System.out.println("status: " + idPairArray[1]);
}
}
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.