Regular expression on a string - java

I have a String like below
String phone = (123) 456-7890
Now I would like my program to verify if that my input is the same pattern as string 'phone'
I did the following
if(phone.contains("([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]")) {
//display pass
}
else {
//display fail
}
It didn't work. I tried with other combinations too. nothing worked.
Question :
1. How can I achieve this without using 'Pattern' like above?
2. How to do this with pattern. I tried with pattern as below
Pattern pattern = Pattern.compile("(\d+)");
Matcher match = pattern.matcher(phone);
if (match.find()) {
//Displaypass
}

String#matches checks if a string matches a pattern:
if (phone.matches("\\(\\d{3}\\) \\d{3}-\\d{4}")) {
//Displaypass
}
The pattern is a regular expression. Therefor I had to escape the round brackets, as they have a special meaning in regex (they denote capturing groups).
contains() only checks if a string contains the substring passed to it.

I'm not going to dive too deeply into regex syntax, but there definitely is something off with your regex.
"([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]"
it containes ( and ) and those have special meaning. Escape them
"\([0-9][0-9][0-9]\) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]"
and you'll also have to escape your \ for the final
"\\([0-9][0-9][0-9]\\) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]"

You can write like:
Pattern pattern = Pattern.compile("\\(\\d{3}\\) \\d{3}-\\d{4}");
Matcher matcher = pattern.matcher(sPhoneNumber);
if (matcher.matches()) {
System.out.println("Phone Number Valid");
}
For more information you can visit this article.

It appears that your problem is that you didn't escape the parentheses, so your Regex is failing. Try this:
\([0-9][0-9][0-9]\) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]

This works
String PHONE_REGEX = "[(]\\b[0-9]{3}\\b[)][ ]\\b[0-9]{3}\\b[-]\\b[0-9]{4}\\b";
String phone1 = "(1234) 891-6762";
Boolean b = phone1.matches(PHONE_REGEX);
System.out.println("is e-mail: " + phone1 + " :Valid = " + b);
String phone2 = "(143) 456-7890";
b = phone2.matches(PHONE_REGEX);
System.out.println("is e-mail: " + phone2 + " :Valid = " + b);
Output:
is phone: (1234) 891-6762 :Valid = false
is phone: (143) 456-7890 :Valid = true

Related

Java: get substring from an string without lang3 utils and StringUtils

I need to get a integer from a string using Java 7.
String is something like:
"\"Transformed\": any-number,
I need to get any-number substring after first match of \"Transformed\": string.
As it has been advised in the comments, if it is a JSON it is more appropriate to use JSON parser. Otherwise you can use regex which might look similar to this:
String line = "\"Transformed\": 10";
String pattern = "Transformed.:.(\\d+)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
if (m.find()) {
System.out.println("Found value: " + m.group(0) );
System.out.println("Found value: " + m.group(1) );
}else {
System.out.println("NO MATCH");
}
You can find more info about current regex here. Please note that this is the simplest case possible and you will probably have to update it, depending on the string format.

Regex not working properly in all cases

I am using a regex to get word from string its working fine in alphanumeric case but return wrong answer if we are used arithmetic operator.
Matcher oMatcher;
Pattern oPattern;
String key = "a++";
oPattern = Pattern.compile("\\b" + key + "\\b");
oMatcher = oPattern.matcher("max winzer® build-a-chair cocktailsessel »luisa« in runder form, zum selbstgestalten");
if (oMatcher.find()) {
System.out.println("True");
}
You have to escape any potential regex special characters in key with Pattern.quote:
oPattern = Pattern.compile("\\b" + Pattern.quote(key) + "\\b");
^^^^^^^^^^^^^

regex matcher check in if logic not working

Hi, you can see my code below. I have some strings Country, rank and grank in my code, initially they will be null, but if regex is mached, it should change the value. But even if regex is matched it is not changing the value it is always null. If I remove all if statements and append the string it works fine, but if match is not found it is throwing an exception. Please let me know how can I check this in if logic.
System.err.println(content);
Pattern c = Pattern.compile("NAME=\"(.*)\" RANK");
Pattern r = Pattern.compile("\" RANK=\"(.*)\"");
Pattern gr = Pattern.compile("\" TEXT=\"(.*)\" SOURCE");
Matcher co = c.matcher(content);
Matcher ra = r.matcher(content);
Matcher gra = gr.matcher(content);
co.find();
ra.find();
gra.find();
String country = null;
String Rank = null;
String Grank = null;
if (co.matches()) {
country = co.group(1);
}
if (ra.matches()) {
Rank = ra.group(1);
}
if (gra.matches()) {
Grank = gra.group(1);
}
You have to escape a single \ - use double \\ then it should work.
Tried this?
while (co.find()) {
System.out.print("Start index: " + co.start());
System.out.print(" End index: " + co.end() + " ");
System.out.println(co.group());
}
Personally I can't make your program work with / without the if so it's not a problem of logic but just a problem that it doesn't match the string for me
So I changed it to get something working, maybe you can use it :)
String content = "NAME=\"salut\" RANK=\"pouet\" TEXT=\"text\" SOURCE";
System.out.println(content);
System.out.println(content.replaceAll(("NAME=\"(.*)\"\\sRANK=\"(.*)\"\\sTEXT=\"(.*)\" SOURCE"), "$1---$2---$3"));
Output
NAME="salut" RANK="pouet" TEXT="text" SOURCE
salut---pouet---text

How to take a substring using pattern match

I have
String content= "<a data-hovercard=\"/ajax/hovercard/group.php?id=180552688740185\">
<a data-hovercard=\"/ajax/hovercard/group.php?id=21392174\">"
I want to get all the id between "group.php?id=" and "\""
Ex:180552688740185
Here is my code:
String content1 = "";
Pattern script1 = Pattern.compile("group.php?id=.*?\"");
Matcher mscript1 = script1.matcher(content);
while (mscript1.find()) {
content1 += mscript1.group() + "\n";
}
But for some reason it does not work.
Can you give me some advice?
Why are you using .*? to match the id. .*? will match every character. You just need to check for digits. So, just use \\d.
Also, you need to capture the id and then print it.
// To consider special characters as literals
String str = Pattern.quote("group.php?id=") + "(\\d*)";
Pattern script1 = Pattern.compile(str);
// Your matcher line
while (mscript1.find()) {
content += mscript1.group(1) + "\n"; // Capture group 1 contains your id
}

String manipulation using Java regexp

I have a String in this format:
mydb://<user>:<password>#<host>:27017
And I would like to use Java regexp in order to extract the <user> and <password> strings from the String. What would be the best way doing so?
EDIT:
I would like to be able to use this regexp in the String's replace method so that I'm left only with the relevant user and password Strings
You can use this regex (Pattern)
Pattern p = Pattern.compile("^mydb://([^:]+):([^#]+)#[^:]+:\\d+$");
And then capture group #1 and #2 will have your user and password respectively.
Code:
String str = "mydb://foo:bar#localhost:27017";
Pattern p = Pattern.compile("^mydb://([^:]+):([^#]+)#[^:]+:\\d+$");
Matcher matcher = p.matcher(str);
if (matcher.find())
System.out.println("User: " + matcher.group(1) + ", Password: "
+ matcher.group(2));
OUTPUT:
User: foo, Password: bar
EDIT: Based on your comments: if you want to use String methods then:
String regex = "^mydb://([^:]+):([^#]+)#[^:]+:\\d+$";
String user = str.replaceAll(regex, "$1");
String pass = str.replaceAll(regex, "$2")

Categories