regex to only allow a range of doubles - java

I have a TextField where the input should be limited between 1.00 and 5.00.
I tried "\\d+\\.\\d+", [0-9]{1,5}(\.[0-9]+)? but neither worked, understandably.
Thanks.

As noted in a comment, there are input field types that will do this check for you. Answering your literal question, however, you can use this:
^([1-4]\.[0-9]{2})|(5\.00)$
You need to handle the 5.00 end of the range specially.

If you need double on exactly 2-digit precision you can use
^[1-5]{1}\.[0-9]{2}$

^[1-4](\\.\\d{1,2})?|5(\\.0{1,2})?$

This will validate 1.00 to 5.00 to two decimal places.
^([1-4]\\.[0-9]{2})$|(5\\.00)$
Example
// String to be scanned to find the pattern.
String line = "1.00";
String pattern = "^([1-4]\\.[0-9]{2})$|(5\\.00)$";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
}else {
System.out.println("NO MATCH: " + line);
}
line = "5.0000";
m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
}else {
System.out.println("NO MATCH: " + line);
}

Related

Regex in Java not working while same regex is working in shell

I want to replace all :variable (word starting with :) with ${variable}$.
For example,
:aks_num with ${aks_num}$
:brn_num with ${brn_num}$
Following is my code, which does not work:
public static void main(String[] argv) throws Exception
{
CharSequence chSeq = "AND ((:aks_num = -1) OR (aks_num = :aks_num AND ((:brn_num = -1) OR (brn_num = :brn_num))))";
// replaceAll also not working
//String s = chSeq.replaceAll(":\\([a-z_]*\\)","\\${ $1 \\}$");
Pattern p = Pattern.compile(":\\([a-z_]*\\)");
Matcher m = p.matcher(chSeq);
if (m.find()) {
System.out.println("Found value: " + m.group(0) );
System.out.println("Found value: " + m.group(1) );
System.out.println("Found value: " + m.group(2) );
} else {
System.out.println("NO MATCH");
}
}
While in shell script the following regex works perfectly:
s/:\([a-z_]*\)/${\1}$/g
:\\([a-z_]*\\) (with escaped parenthesis) means that you want to match expressions like :(aks_num). Obviously, there are no such expression in the input string. That explains why there are no matches.
Instead, if you want to use parenthesis in order to capture some variables, you should not escape the parenthesis.
Example :
CharSequence chSeq = "AND ((:aks_num = -1) OR (aks_num = :aks_num AND ((:brn_num = -1) OR (brn_num = :brn_num))))";
Pattern p = Pattern.compile(":([a-z_]*)");
Matcher m = p.matcher(chSeq);
while (m.find()) {
System.out.println("Found value: " + m.group(0)+". Captured : "+m.group(1));
}
Output:
Found value: :aks_num. Captured : aks_num
Found value: :aks_num. Captured : aks_num
Found value: :brn_num. Captured : brn_num
Found value: :brn_num. Captured : brn_num
CharSequence chSeq = "AND ((:aks_num = -1) OR (aks_num = :aks_num AND ((:brn_num = -1) OR (brn_num = :brn_num))))";
// replaceAll also not working
//String s = chSeq.replaceAll(":\\([a-z_]*\\)","\\${ $1 \\}$");
Pattern p = Pattern.compile(":(\\w+)");
Matcher m = p.matcher(chSeq);
while (m.find()) {
System.out.println("Found value: " + m.group(1) );
}
Ideone Demo
Working fine with replaceAll
Pattern p = Pattern.compile("(:\\w+)");
Matcher m = p.matcher(x);
x = m.replaceAll("\\${$1}\\$");
You don't need to escape the parentheses, so
Pattern.compile(":([a-z_]*)");
should work.
I believe you got confused with the Java's regex syntax that is different from regular sed syntax. You do not need to escape parentheses to make them "special" grouping operators. Vice versa, in Java, when you escape parentheses, they start matching literal ( and ) symbols.
In the replacement pattern, $ must be escaped for the regex engine to replace with literal $ symbols, but you do not need to escape braces there.
So, just use
.replaceAll(":([a-z_]+)", "\\${$1}\\$")
See the IDEONE demo
I suggest the + quantifier because I doubt you need to match a : followed with a space, or digits - any non-letter.
BTW, you do not need any /g flag in Java since replaceAll will replace all matches with the provided replacement pattern.
NOTE: you can further adjust the pattern to match all letters/digits/underscores with ":(\\w+)". Or just alphanumerics/underscore: ":([\\p{Alnum}_]+)".

match a string with text and store the next text

I have a string which contains some text (in Greek language) which was extracted from a pdf.
How can I found a particular text lets say id.name: 123 and then store the number 123?
You can find using a regular expression:
String s = "Έχω ένα string που περιέχει κάποιο κείμενο ( στην ελληνική γλώσσα ), "
+ "το οποίο εξήχθη από ένα PDF .\nΠως μπορώ να ιδρύσω ένα συγκεκριμένο κείμενο "
+ "ας πούμε id.name : 123 και στη συνέχεια να αποθηκεύσετε τον αριθμό 123";
Pattern p = Pattern.compile("id\\.name \\: (\\d+)");
Matcher m = p.matcher(s);
if(m.find()){
System.out.println(m.group(1));
}
Regards.
there are many ways to do it, you can try regular expressions,
for instance let's suppose we have a string call s1 that contain "today is monday" and we can find the word monday, you can do that by:
String matcher = "today is monday";
Pattern p2 = Pattern.compile(".*monday.*");
Matcher m2 = p2.matcher(matcher);
boolean b2 = m2.matches();
if(b2 == true)
{
System.out.println(p2 + " found");
}
else
{
System.out.println(p2 + "no found");
}
}

Java multiple regular expression search

I have a string some thing like this:
If message contains sensitive info like: {Password:123456, tmpPwd : tesgjadgj, TEMP_PASSWORD: kfnda}
My pattern should look for the particular words Password or tmpPwd or TEMP_PASSWORD.
How can I create a pattern for this kind of search?
I think you are looking for the values after these words. You need to set capturing groups to extract those values, e.g.
String content = "If message contains sensitive info like: {Password:123456, tmpPwd : tesgjadgj, TEMP_PASSWORD: kfnda} ";
Pattern p = Pattern.compile("\\{Password\\s*:\\s*([^,]+)\\s*,\\s*tmpPwd\\s*:\\s*([^,]+)\\s*,\\s*TEMP_PASSWORD:\\s*([^,]+)\\s*\\}");
Matcher m = p.matcher(content);
while (m.find()) {
System.out.println(m.group(1) + ", " + m.group(2) + ", " + m.group(3));
}
See IDEONE demo
This will output 123456, tesgjadgj, kfnda.
To just find out if there are any of the substrings, use contains method:
System.out.println(content.contains("Password") ||
content.contains("tmpPwd") ||
content.contains("TEMP_PASSWORD"));
See another demo
And if you want a regex-solution for the keywords, here it is:
String str = "If message contains sensitive info like: {Password:123456, tmpPwd : tesgjadgj, TEMP_PASSWORD: kfnda} ";
Pattern ptrn = Pattern.compile("Password|tmpPwd|TEMP_PASSWORD");
Matcher m = ptrn.matcher(str);
while (m.find()) {
System.out.println("Match found: " + m.group(0));
}
See Demo 3
Finally I am using it like as per my requirement .
private final static String censoredWords =
"(?i)PASSWORD|pwd";
The (?i) makes it case-insensitive

Regular expression for mobile number vaidation?

I have following regular expression for following mobile numbers:
^(([+]|[0]{2})([\\d]{1,3})([\\s-]{0,1}))?([\\d]{10})$
Valid numbers are:
+123-9854875847
00123 9854875847
+123 9854875847
9878757845
Above expression will not validate if user enter 9 or 11 digit mobile number but if user enter 9 or 11 digit number with +123 or +91 respectively then it is getting validate because in this part of expression ([\\d]{1,3}) last two digits are optional.
So, any way to make this part ([\\s-]{0,1}))?([\\d]{10}) not to get combine with this part ([\\d]{1,3})?
The question is somewhat unclear, but I presume you want to split the number and the country code.
This is quite easy to do by extracting groups. group(i) is the i-th thing in brackets.
I also applied these simplifications: [\\d] = \\d, {0,1} = ?, [+] = \\+, [0]{2} = 00.
Code:
String regex = "^((\\+|00)(\\d{1,3})[\\s-]?)?(\\d{10})$";
String str = "+123-9854875847";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
if (m.matches())
{
System.out.println("Country = " + m.group(3));
System.out.println("Data = " + m.group(4));
}
Output:
Country = 123
Data = 9854875847
Alternative using non-matching groups (?:): (so you can use group(1) and group(2))
String regex = "^(?:(?:\\+|00)(\\d{1,3})[\\s-]?)?(\\d{10})$";
String str = "+123-9854875847";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
if (m.matches())
{
System.out.println("Country = " + m.group(1));
System.out.println("Data = " + m.group(2));
}
Reference.
Related test.
As long as the extension is always separated from the rest of the phone number, your regex will work fine. If there is no such separation, there is no way to correctly validate a phone number.
Also keep in mind that both extensions and phone numbers can vary in length from country to country, so there is no regex that will solve all cases. If you can produce a list of allowed extensions, you can work that into the regex and get better matches, but for many groups of arbitrary length of digits you will get many wrong matches.
I have simplified your regex a bit, so oyu can see #Dukeling's suggestions in practice. Your regex on top, mine on the bottom.
^(([+]|[0]{2})([\\d]{1,3})([\\s-]{0,1}))?([\\d]{10})$
^( (\\+|00) \\d{1,3} [\\s-]?)? \\d{10} $
try {
String mobile_number="india number +919979045000\n" +
"india number 9979045000\n" +
"china number +86 591 2123654\n" +
"Brazil number +55 79 2012345\n" +
"it is test all string get mobile number all country"+
"Ezipt +20 10 1234567\n" +
"France +33 123456789\n" +
"Hong Kong +852 1234 5456\n" +
"Mexico +52 55 12345678"+
"thanks";
Pattern p = Pattern.compile("\\(?\\+[0-9]{1,3}\\)? ?-?[0-9]{1,3} ?-?[0-9]{3,5} ?-?[0-9]{5}( ?-?[0-9]{3})? ?(\\w{1,10}\\s?\\d{1,6})?");
List<String> numbers = new ArrayList<String>();
//mobile_number= mobile_number.replaceAll("\\-", "");
Matcher m = p.matcher("" + mobile_number);
while (m.find()) {
numbers.add(m.group());
}
p = Pattern.compile("\\(?\\+[0-9]{1,3}\\)? ?-?[0-9]{1,3} ?-?[0-9]{3,5} ?-?[0-9]{4}( ?-?[0-9]{3})? ?(\\w{1,10}\\s?\\d{1,6})?");
m = p.matcher("" + mobile_number);
while (m.find()) {
numbers.add(m.group());
}
p = Pattern.compile("((?:|\\+)([0-9]{5})(?: |\\-)(0\\d|\\([0-9]{5}\\)|[1-9]{0,5}))");
m = p.matcher("" + mobile_number);
while (m.find()) {
numbers.add(m.group());
}
p = Pattern.compile("[0-9]{10}|\\(?\\+[0-9]{1,3}\\)?-?[0-9]{3,5} ?-?[0-9]{4}?");
m = p.matcher("" + mobile_number);
while (m.find()) {
numbers.add(m.group());
}
String numberArray=numbers.toString();
System.out.print(""+numberArray);
// final result
/* [+919979045000, +86 591 2123654, +33 123456789, +52 55 12345678, +919979045000, +86 591 2123654, +55 79 2012345, +20 10 1234567, +33 123456789, +852 1234 5456, +52 55 12345678, +919979045000, 9979045000] */
} catch (Exception e) {
e.printStackTrace();
}
Best way to take input in two parts i.e country code and mobile number.
In that case you can easily validate it (both country code and mobile number) with regex.

REGEX : How to escape []?

I'm working on strings like "[ro.multiboot]: [1]". How do I just select 1(it can also be 0) out of this string?
I am looking for a regex in Java.
Usually, you would do something like (assuming 0 and 1 were the only options):
^.*\[([01])\].*$
If you only wanted the value for ro.multiboot, you could change it to something like:
^.*\[ro.multiboot\].*\[([01])\].*$
(depending on how complex any of the non-bracketed stuff is allowed to be).
These would both basically only extract the value between square brackets if it were zero or one, and capture it into a capture variable so you could use it.
Of course, regex is not a world-wide standard, nor are the environments in which you use it. That means it depends a lot on your actual environment how you will actually code this up.
For Java, the following sample program may help:
import java.util.regex.*;
class Test {
public static void main(String args[]) {
Pattern p = Pattern.compile("^.*\\[ro.multiboot\\].*\\[([01])\\].*$");
String str;
Matcher m;
str = "[ro.multiboot]: [0]";
m = p.matcher (str);
if (m.find()) {
System.out.println ("str0 has " + m.group(1));
}
str = "[ro.multiboot]: [1]";
m = p.matcher (str);
if (m.find()) {
System.out.println ("str1 has " + m.group(1));
}
str = "[ro.multiboot]: [2]";
m = p.matcher (str);
if (m.find()) {
System.out.println ("str2 has " + m.group(1));
}
}
}
This results in (as expected):
str0 has 0
str1 has 1
#paxdiablo's regexps are correct, but complete answer for "How do I just select 1(it can also be 0) out of this string?" is:
1. very simple solution
String input = "[ro.multiboot]: [1]";
String matched = input.replaceFirst( "^.*\\[ro.multiboot\\].*\\[([01])\\].*$", "$1" );
2. same functionality, more complicated but with better performance
String input = "[ro.multiboot]: [1]";
Pattern p = Pattern.compile( "^.*\\[ro.multiboot\\].*\\[([01])\\].*$" );
Matcher m = p.matcher( input );
String matched = null;
if ( m.matches() ) matched = m.group( 1 );
Performance is better because the pattern is compiled just once (for example when you are matching array os such Strings);
Notes:
in both examples the group is part of regexps between ( and ) (if not escaped)
in Java you have to use \\[, because \[ returns error - it is not correct escape sequence for String

Categories

Resources