Java Browser, Dynamic string Matcher Pattern - java

I have the following code that uses a specific string and uses the matcher and pattern to draw a link, I also have a method that returns the html code as a string, my problem is that I dont know how to call it so that when the following method runs it uses the dynamic string instead of a static one, I tried using the dynamic string name inside the search but it gave me an error saying that it cannot be compiled since im trying to use a dynamic string instead of a static one, any hints or help would be appreciated, if you need any of my other classes and or methods feel free to ask.
String stringToSearch = "<a>www.google.com</a> ";
Pattern p = Pattern.compile("<a>(\\S+)</a>");
Matcher m = p.matcher(stringToSearch);
if (m.find())
{
String codeGroup = m.group(1);
System.out.format("'%s'\n", codeGroup);
}
}
}

This isn't really a 'design-patterns' question, it is more to do with just knowing how to pass arguments properly into methods.
The Pattern.compile(String) method takes a string as input. That string doesn't have to be a constant. You can pass that string in as a parameter, I've even put it into a 'helper' method to demonstrate that.
public public void someMethod(){
String stringToSearch = "<a>www.google.com</a> ";
String matchPattern = "<a>(\\S+)</a>";
if (doesMatch(matchPattern,stringToSearch)){
String codeGroup = m.group(1);
System.out.format("'%s'\n", codeGroup);
}
}
public static boolean doesMatch(String pattern, String stringToSearch){
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(stringToSearch);
return m.find();
}
to show you what I think you mean...
{
// code...
String stringToSearch = getContent(); //might have parameters here or not
String matchPattern = "<a>(\\S+)</a>";
if (doesMatch(matchPattern,stringToSearch)){
String codeGroup = m.group(1);
System.out.format("'%s'\n", codeGroup);
}
}
public static boolean doesMatch(String pattern, String stringToSearch){
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(stringToSearch);
return m.find();
}

Related

I Want to extract a certain number from string in java but not able to do so

I have a string like String a = "I have 102 string but 123453 is best"
So, In the above string i want to extract only 123453
This string keep getting changes but i always want to get that second number from this string.
What is the best possible way to do this?
Here is a complete example. First define your pattern:
Pattern p = Pattern.compile("[0-9]+");
Then define the string you want to test
String test = "I have 102 string but 123453 is best";
Create a matcher for that string
Matcher matcher = p.matcher(test);
Find once
matcher.find(); // find once
Find again, and if found, get the string
if (matcher.find()) { // find twice
System.out.println(matcher.group());
}
For a complete, minimal and repeatable example, consider defining a method and defining the pattern as a constant:
static final Pattern P = Pattern.compile("[0-9]+");
static String findSecondNumber(String test) {
Matcher matcher = P.matcher(test);
matcher.find(); // find once
if (matcher.find()) { // find twice
return matcher.group();
}
return null; // or alternatively return an empty string or a default value
}
Where matcher.group() returns the full match found; see also the documentation here.
It can be done in a single find() with capturing groups. Here is how:
String a = "I have 102 string but 123453 is best"
Pattern p = Pattern.compile("^.*\d+.*(\d*).*$");
Matcher m = p.matcher(a);
if (m.find()) {
System.out.println(m.group(1)); // this will print 123453
}

How to match with two regex Expression?

I should check if that string is valid. So i can i check UUID parts with this regex expression
private String UUID = "([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})"
private String url = "customers/00000000-0000-0000-0000-000000000111/areas/00000000-0000-0000-0000-000000000222/orders/00000000-0000-0000-0000-000000000555/invoices/00000000-0000-0000-0000-000000000777/employees/2018-10-31T00:27:31.205+0000.jpg"
like this
Pattern JPG_PATTERN = Pattern.compile(
String.format("customers/%s/areas/%<s/orders/%<s/invoices/%<s/employees/", UUID));
Matcher m = JPG_PATTERN.matcher(url);
if (m.find()) {
System.out.println("found);
}
But when i add another regex to check last part of the string. It doesn't work.
private String EXTENSION = "(?:mov|jpg)";
Pattern JPG_PATTERN = Pattern.compile(
String.format("customers/%s/areas/%<s/orders/%<s/invoices/%<s/employees/%s", UUID, EXTENSION));
Matcher m = JPG_PATTERN.matcher(url);
if (m.find()) {
System.out.println("found);
}
How can use these two apart regex expression and check if the string is valid?
Your regex does not match filename: 2018-10-31T00:27:31.205+0000.
Change extension regex to String EXTENSION = ".+(?:mov|jpg)";
And change find to matches, otherwise .jpg1 is considered valid. Here is full the code:
private static String UUID = "([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})";
private static String url = "customers/00000000-0000-0000-0000-000000000111/areas/00000000-0000-0000-0000-000000000222/orders/00000000-0000-0000-0000-000000000555/invoices/00000000-0000-0000-0000-000000000777/employees/2018-10-31T00:27:31.205+0000.jpg";
private static String EXTENSION = ".+(?:mov|jpg)";
public static void main(String[] args) {
Pattern JPG_PATTERN = Pattern.compile(String.format("customers/%s/areas/%<s/orders/%<s/invoices/%<s/employees/%s", UUID, EXTENSION));
Matcher m = JPG_PATTERN.matcher(url);
if (m.matches()) {
System.out.println("found");
} else {
System.out.println("not found");
}
}
Here is a fixed version of your code. The blocker I saw on your end seemed to be a misunderstanding of how String#format works. Because you are trying to bind more than one placeholder, I suggest just using %s everywhere and then specifying each string explicitly. Note that the pattern you want to use for the final path component for the extension is slightly different than what you suggested.
String UUID = "([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})";
String EXTENSION = ".*(?:mov|jpg)$";
String pattern = String.format("^customers/%s/areas/%s/orders/%s/invoices/%s/employees/%s", UUID, UUID, UUID, UUID, EXTENSION);
System.out.println(pattern);
^customers/([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})/areas/
([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})/orders/
([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})/invoices/
([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})/employees/.*(?:mov|jpg)$
Follow the link below for a running regex demo which shows that the above pattern matched your test URL.
Demo

Find all occurrences of a regex pattern in a line

My String is like this (one single line):
String input = "Details of all persons. Person=details=John Smith-age-22; Person=details=Alice Kohl-age-23; Person=details=Ram Mohan-city-Dallas; Person=details=Michael Jack-city-Boston;"
I want to find out using regex matching all the persons with its details (basically text from details upto the char prior to semicolon). I am interested in finding:
details=John Smith-age-22
details=Alice Kohl-age-23
details=Ram Mohan-city-Dallas
details=Michael Jack-city-Boston
Can someone tell me how to do this ? Sorry, I could not find any example like that over the net. Thanks.
You can try this code.
public static void main(String[] args) {
String input = "Details of all persons. Person=details=John Smith-age-22; Person=details=Alice Kohl-age-23; Person=details=Ram Mohan-city-Dallas; Person=details=Michael Jack-city-Boston;";
Pattern pattern = Pattern.compile("(?<=Person=).*?(?=;)");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
String str = matcher.group();
System.out.println(str);
}
}
No assertion
public static void main(String[] args) {
String input = "Details of all persons. Person=details=John Smith-age-22; Person=details=Alice Kohl-age-23; Person=details=Ram Mohan-city-Dallas; Person=details=Michael Jack-city-Boston;";
Pattern pattern = Pattern.compile("Person=.*?;");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
String str = matcher.group();
System.out.println(str.substring(7, str.length()-1));
}
}
I suspect you will find it easiest if you put the fields you are looking for into groups so that you can extract the details you want.
Something like:
Pattern personPattern = Pattern.compile("Person=details=(\\w+)-(age-\\d+|city-\\w+); ");
Matcher matcher = personPattern.match(input);
while (matcher.find()) {
String name = matcher.group(1);
String field = matcher.group(2);
...
}

Unable to Parse reqular expression in JAVA

This is my code,
String xyz = "{\"status\":\"ok\",\"data\":[{\"RatingCount\":4}], [{\"RatingCount\":1}], [{\"RatingCount\":1}]\"code\":1}";
String pattern = ".*],\\s*\\[.*";//"(.*)(],\\s.*\\[)(.*)";
Pattern p1 = Pattern.compile(pattern);
Matcher m1 = p1.matcher(xyz);
boolean b = m1.matches();
System.out.println(b);
I would like to replace pattern '], [' with "".
I used replaceAll but no luck
Check it in working Fiddle
Use the regex as below
String pattern = "\],[ ]*\[";
xyz =xyz.replaceAll("]\s*,\s*\[", "],[");
This worked like charm and also this link helped me alot http://regexr.com/
Thank you for all your inputs!
The output of this block is: {"status":"ok","data":[{"RatingCount":4}{"RatingCount":1}{"RatingCount":1}]"code":1}
public static void main(String[] args) {
String str = "{\"status\":\"ok\",\"data\":[{\"RatingCount\":4}], [{\"RatingCount\":1}], [{\"RatingCount\":1}]\"code\":1}";
System.out.println(replace(str, "\\],\\s+\\["));
}
public static String replace(String str, String regex) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
return matcher.replaceAll("");
}

Java Pattern match

I've a long template from which I need to extract certain strings based on certain patterns. When I went through some examples I found that use of quantifiers is good in such situations.For example following is my template, from which I need to extract while and doWhile.
This is a sample document.
$while($variable)This text can be repeated many times until do while is called.$endWhile.
Some sample text follows this.
$while($variable2)This text can be repeated many times until do while is called.$endWhile.
Some sample text.
I need to extract the whole text, starting from $while($variable) till $endWhile. I then need to process the value of $variable. After that I need to insert the text between $while and $endWhile to the original text.
I've the logic of extracting the variable. But I'm not sure how to use quantifiers or pattern match here.
Can someone please provide me a sample code for this? Any help will be greatly appreciated
You can use a rather simple regex-based solution here with a Matcher:
Pattern pattern = Pattern.compile("\\$while\\((.*?)\\)(.*?)\\$endWhile", Pattern.DOTALL);
Matcher matcher = pattern.matcher(yourString);
while(matcher.find()){
String variable = matcher.group(1); // this will include the $
String value = matcher.group(2);
// now do something with variable and value
}
If you want to replace the variables in the original text, you should use the Matcher.appendReplacement() / Matcher.appendTail() solution:
Pattern pattern = Pattern.compile("\\$while\\((.*?)\\)(.*?)\\$endWhile", Pattern.DOTALL);
Matcher matcher = pattern.matcher(yourString);
StringBuffer sb = new StringBuffer();
while(matcher.find()){
String variable = matcher.group(1); // this will include the $
String value = matcher.group(2);
// now do something with variable and value
matcher.appendReplacement(sb, value);
}
matcher.appendTail(sb);
Reference:
Methods of the Pattern Class
(Sun Java Tutorial)
Methods of the Matcher Class
(Sun Java Tutorial)
Pattern JavaDoc
Matcher JavaDoc
public class PatternInString {
static String testcase1 = "what i meant here";
static String testcase2 = "here";
public static void main(String args[])throws StringIndexOutOfBoundsException{
PatternInString testInstance= new PatternInString();
boolean result = testInstance.occurs(testcase1,testcase2);
System.out.println(result);
}
//write your code here
public boolean occurs(String str1, String str2)throws StringIndexOutOfBoundsException
{ int i;
boolean result=false;
int num7=str1.indexOf(" ");
int num8=str1.lastIndexOf(" ");
String str6=str1.substring(num8+1);
String str5=str1.substring(0,num7);
if(str5.equals(str2))
{
result=true;
}
else if(str6.equals(str2))
{
result=true;
}
int num=-1;
try
{
for(i=0;i<str1.length()-1;i++)
{ num=num+1;
num=str1.indexOf(" ",num);
int num1=str1.indexOf(" ",num+1);
String str=str1.substring(num+1,num1);
if(str.equals(str2))
{
result=true;
break;
}
}
}
catch(Exception e)
{
}
return result;
}
}

Categories

Resources