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
Related
I have string like
Strig foo = "PrinciplexbxbxbxbxbxbTeachershshshshshhsClassdhdhdhhdhdhdList[something to be extracted]jdjdjdj"
I want output to be "something to be extracted" where regex of string is Principle*Teacher*Class*List[*]*.
After this make a new string
Strig foo = "PrinciplexbxbxbxbxbxbTeachershshshshshhsClassdhdhdhhdhdhdList[something new]jdjdjdj"
If you want to get something to be extracted then you can extract every thing between the two brackets \[(.*?)\], you can use Pattern like this :
String foo = ...;
String regex = "\\[(.*)\\]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(foo);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
If you want to replace it you can use replaceAll with the same regex :
foo = foo.replaceAll("\\[.*?\\]", "[something new]");
regex demo
If your String is always in the same format and contains the words Principle, Teachers and Class followed by [some text], then this is the Regex you need :
Principle\\w*Teachers\\w*Class\\w*\\[([\\s\\w]+)\\]\\w*
The matching group in \\[([\\s\\w]+)\\] will match the string you need.
Your code would be like this:
final String regex = "Principle\\w*Teachers\\w*Class\\w*\\[([\\s\\w]+)\\]\\w*";
final String string = "Strig foo = \"PrinciplexbxbxbxbxbxbTeachershshshshshhsClassdhdhdhhdhdhdList[something to be extracted]jdjdjdj\"\n";
string.replaceAll(regex, "something new");
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();
}
I am using regex in java to get a specific output from a list of rooms at my University.
A outtake from the list looks like this:
(A55:G260) Laboratorium 260
(A55:G292) Grupperom 292
(A55:G316) Grupperom 316
(A55:G366) Grupperom 366
(HDS:FLØYEN) Fløyen (appendix)
(ODO:PC-STUE) Pulpakammeret (PC-stue)
(SALEM:KONF) Konferanserom
I want to get the value that comes between the colon and the parenthesis.
The regex I am using at the moment is:
pattern = Pattern.compile("[:]([A-Za-z0-9ÆØÅæøå-]+)");
matcher = pattern.matcher(room.text());
I've included ÆØÅ, because some of the rooms have Norwegian letters in them.
Unfortunately the regex includes the building code also (e.g. "A55") in the output... Comes out like this:
A55
A55
A55
:G260
:G292
:G316
Any ideas on how to solve this?
The problem is not your regular expression. You need to reference group(1) for the match result.
while (matcher.find()) {
System.out.println(matcher.group(1));
}
However, you may consider using a negated character class instead.
pattern = Pattern.compile(":([^)]+)");
You can try a regex like this :
public static void main(String[] args) {
String s = "(HDS:FLØYEN) Fløyen (appendix)";
// select everything after ":" upto the first ")" and replace the entire regex with the selcted data
System.out.println(s.replaceAll(".*?:(.*?)\\).*", "$1"));
String s1 = "ODO:PC-STUE) Pulpakammeret (PC-stue)";
System.out.println(s1.replaceAll(".*?:(.*?)\\).*", "$1"));
}
O/P :
FLØYEN
PC-STUE
Can try with String Opreations as follows,
String val = "(HDS:FLØYEN) Fløyen (appendix)";
if(val.contains(":")){
String valSub = val.split("\\s")[0];
System.out.println(valSub);
valSub = valSub.substring(1, valSub.length()-1);
String valA = valSub.split(":")[0];
String valB = valSub.split(":")[1];
System.out.println(valA);
System.out.println(valB);
}
Output :
(HDS:FLØYEN)
HDS
FLØYEN
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class test
{
public static void main( String args[] ){
// String to be scanned to find the pattern.
String line = "(HDS:FLØYEN) Fløyen (appendix)";
String pattern = ":([^)]+)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
while (m.find()) {
System.out.println(m.group(1));
}
}
}
I have following 2 urls:
https://docs.google.com/a/abc.com/spreadsheet/ccc?key=0Aj9Oa8x5fqsL678FNhOUF0ZEN5b25iVVZNdjdUQm9mM1E&usp=drive_web#gid=0
https://docs.google.com/a/abc.com/file/d/0Aj9Oa8x5fqsL678FNhOUF0ZEN5b25iVVZNdjdUQm9mM1E/edit
I am using following regex:
Pattern.compile(".*key=|/d/(.[^&/])")
as a result of it I want that the matcher.group() returns both urls upto fileId(0Aj9Oa8x5fqsL678FNhOUF0ZEN5b25iVVZNdjdUQm9mM1E) part and matcher.group(1) returns the fileId.
but I am not getting these results.
you fell victim to the precedence rules in regex expressions and forgot the repetition specifier for your character class. try
Pattern.compile("(key=|/d/)([^&/]+)")
your result will be in $2.
If you don't need to use a regex, then use URI:
private static final Pattern PARAM_SEPARATOR = Pattern.compile("&");
private static final Pattern PATH_MATCHER = Pattern.compile("/file/d/([^/]+)");
// In query parameter...
public static String getKeyQueryParamFromURI(final String input)
{
final URI uri = URI.create(input);
final String params = uri.getQuery();
if (params == null)
return null;
for (final String param: PARAM_SEPARATOR.split(input))
if (param.startsWith("key="))
return param.substring(4);
return null;
}
// In path...
public static String getPathMatcherFromURI(final String input)
{
final URI uri = URI.create(input);
final String path = uri.getPath();
if (path == null)
return null;
final Matcher m = PATH_MATCHER.matcher(input);
return m.find() ? m.group(1) : null;
}
Note that unlike a regex, you will receive the result unescaped. If for instance the URI reads key=a%20b, this will return you "a b"!
If you insist on using a regex (why?), then do that instead for the query parameter:
private static final Pattern PATTERN = Pattern.compile("(?<=[?&])key=([^&]+)");
public static String getKeyQueryParamFromURI(final String input)
{
final Matcher m = PATTERN.matcher(input);
return m.find() ? m.group(1) : null;
}
But you'll have to unescape the parameter value yourself...
It's prefer for two different regex pattern to split the regex statement and not use |(OR).
With using different pattern you will have the first capture group the result you wanted.
Pattern1:
.*key=(.*)=.*
Pattern2:
.*\/file\/?\/(.*)\/.*
I have following string
String S1="S1_T1_VIEW";
I want it to be split and assign to string like this:
String permission = "VIEW";
String component = "S1_T1";
String parent = "S1";
I tried using using S1.split() function it didn't help much.
String can also be like this
String S1="S1_T1_C1_DELETE";
That time results should be
String permission = "DELETE";
String component = "S1_T1_C1";
String parent = "S1_T1";
Any suggestions would be helpful .
Thanks in advance
I'm assuming the following:
permission is the part of S1 following the last underscore.
component is the part of S1 preceding the last underscore.
parent is the part of component preceding its last underscore.
If so, try the following, perhaps? This is essentially just a literal interpretation of the above rules, splitting the string by finding the appropriate underscores.
int lastUnderscore = S1.lastIndexOf("_");
String permission = S1.substring(lastUnderscore + 1);
String component = S1.substring(0, lastUnderscore);
lastUnderscore = component.lastIndexof("_");
String parent = component.substring(0, lastUnderscore);
We could also use a regex.
private static final Pattern pattern = Pattern.compile("^((.+)_[^_]+)_([^_]+)$");
final Matcher matcher = pattern.matcher(input);
if (!matcher.matches()) {
return null;
}
String permission = matcher.group(3);
String component = matcher.group(1);
String parent = matcher.group(2);
Demo: http://ideone.com/NhZPI2