Giving inputs to java regex - java

I have a regex like below one :
"\\t'AUR +(username) .*? /ROLE=\"(my_role)\".*$"
username and my_role parts will be given from args. So they always change when the script is starting. So how can i give parameters to that part of regex ?
Thanks for your helps.

Define regex like this:
String fmt = "\\t'AUR +(%s) .*? /ROLE=\"(%s)\".*$";
// assuming userName and myRole are your arguments
String regex = String.format(fmt, userName, myRole);

You should escape special characters in dynamic strings using Pattern.quote. To put the regex parts together you can simply use string concatenation like this:
String quotedUsername = Pattern.quote(username);
String quotedRole = Pattern.quote(my_role);
String regexString = "\\t'AUR +(" + quotedUsername +
") .*? /ROLE=\"(" + quotedRole + ")\".*$";
I think mixing regular expressions with format strings when using String.format can make the regex harder to understand.

Use string format or straight string concat to construct the regex before passing it to compile ...

Try this for an example:
String patternString = "\\t'AUR +(%s) .*? /ROLE=\"(%s)\".*$";
String formatted = String.format(patternString, username,my_role);
System.out.println(formatted);
Pattern pattern = Pattern.compile(patternString);
You can run a working example here: http://ideone.com/93YeNg

Related

Split a string in java based on custom logic

I have a string
"target/abcd12345671.csv"
and I need to extract
"abcd12345671"
from the string using Java. Can anyone suggest me a clean way to extract this.
Core Java
String fileName = Paths.get("target/abcd12345671.csv").getFileName().toString();
fileName = filename.replaceFirst("[.][^.]+$", "")
Using apache commons
import org.apache.commons.io.FilenameUtils;
String fileName = Paths.get("target/abcd12345671.csv").getFileName().toString();
String fileNameWithoutExt = FilenameUtils.getBaseName(fileName);
I like a regex replace approach here:
String filename = "target/abcd12345671.csv";
String output = filename.replaceAll("^.*/|\\..*$", "");
System.out.println(output); // abcd12345671
Here we use a regex alternation to remove all content up, and including, the final forward slash, as well as all content from the dot in the extension to the end of the filename. This leaves behind the content you actually want.
Here is an approach with using regex
String filename = "target/abcd12345671.csv";
var pattern = Pattern.compile("target/(.*).csv");
var matcher = pattern.matcher(filename);
if (matcher.find()) {
// Whole matched expression -> "target/abcd12345671.csv"
System.out.println(matcher.group(0));
// Matched in the first group -> in regex it is the (.*) expression
System.out.println(matcher.group(1));
}

Java String replace All Chars?

i am not familiar with regular expressions maybe one of you can help me. I have a String "46,50 EUR" or "-4.785,20 €" or something similar. I like to remove all chars that are not "0123456789.,-" I tried:
string betrag = "-4.785,20 €";
betrag = betrag.replaceAll("/[^0-9.,-]/", "");
but it wont work. The EUR-Sign will not be removed. Maybe it has something to do with the coding? utf-8 vs. latin1? Or my regular expression is wrong?
Java's regex literals do not require delimiters, so remove the /:
String betrag = "-4.785,20 €";
betrag = betrag.replaceAll("[^0-9.,-]+", "");
System.out.println(betrag); // -4.785,20
you can also use "/d" - it is shortcut for digital characters
but of course the result is the same as mentioned by Tim
String betrag = "-4.785,20 €";
betrag = betrag.replaceAll("[^\d.,-]+", "");
by the way you can easily test your regular expression via some tools/websites - e.g.:
https://www.freeformatter.com/java-regex-tester.html

Regex Redirect URL excludes token

I'm trying to create a redirect URL for my client. We have a service that you specify "fromUrl" -> "toUrl" that is using a java regex Matcher. But I can't get it work to include the token in when it converts it. For example:
/fromurl/login?token=7c8Q8grW5f2Kz7RP1%2FWsqpVB%2FEluVOGfXQdW4I0v82siR2Ism1D8VCvEmKJr%2BKhHhicwPey0uIiTxN049Be8TNsypf
Should be:
/tourl/login?token=7c8Q8grW5f2Kz7RP1%2FWsqpVB%2FEluVOGfXQdW4I0v82siR2Ism1D8VCvEmKJr%2BKhHhicwPey0uIiTxN049Be8TNsypf
but it excludes the token so the result I get is:
/fromurl/login/
/tourl/login/
I tried various regex patterns like: " ?.* and [%5E//?]+)/([^/?]+)/(?.*)?$ and (/*) etc" but no one seems to work.
I'm not that familiar with regex. How can I solve this?
This can be easily done using simple string replace but if you insist on using regular expressions:
Pattern p = Pattern.compile("fromurl");
String originalUrlAsString = "/fromurl/login?token=7c8Q8grW5f2Kz7RP1%2FWsqpVB%2FEluVOGfXQdW4I0v82siR2Ism1D8VCvEmKJr%2BKhHhicwPey0uIiTxN049Be8TNsypf ";
String newRedirectedUrlAsString = p.matcher(originalUrlAsString).replaceAll("tourl");
System.out.println(newRedirectedUrlAsString);
If I understand you correctly you need something like this?
String from = "/my/old/url/login?token=7c8Q8grW5f2Kz7RP1%2FWsqpVB%2FEluVOGfXQdW4I0v82siR2Ism1D8VCvEmKJr%2BKhHhicwPey0uIiTxN049Be8TNsypf";
String to = from.replaceAll("\\/(.*)\\/", "/my/new/url/");
System.out.println(to); // /my/new/url/login?token=7c8Q8grW5f2Kz7RP1%2FWsqpVB%2FEluVOGfXQdW4I0v82siR2Ism1D8VCvEmKJr%2BKhHhicwPey0uIiTxN049Be8TNsypf";
This will replace everything between the first and the last forward slash.
Can you detail more exactly what the original expression is like? This is necessary because the regular expression is based on it.
Assuming that the first occurrence of fromurl should simply be replaced with the following code:
String from = "/fromurl/login?token=7c8Q8grW5f2Kz7RP1%2FWsqpVB%2FEluVOGfXQdW4I0v82siR2Ism1D8VCvEmKJr%2BKhHhicwPey0uIiTxN049Be8TNsypf";
String to = from.replaceFirst("fromurl", "tourl");
But if it is necessary to use more complex rules to determine the substring to replace, you can use:
String from = "/fromurl/login?token=7c8Q8grW5f2Kz7RP1%2FWsqpVB%2FEluVOGfXQdW4I0v82siR2Ism1D8VCvEmKJr%2BKhHhicwPey0uIiTxN049Be8TNsypf";
String to = "";
String regularExpresion = "(<<pre>>)(fromurl)(<<pos>>)";
Pattern pattern = Pattern.compile(regularExpresion);
Matcher matcher = pattern.matcher(from);
if (matcher.matches()) {
to = from.replaceAll(regularExpresion, "$1tourl$3");
}
NOTE: pre and pos targets are referencial because I don't know the real expresion of the url
NOTE 2: $1 and $3 refer to the first and the third group
Although existing answers should solve the issue and some are similar, maybe below solution would be of help, with quite an easy regex being used (assuming you get input of same format as your example):
private static String replaceUrl(String inputUrl){
String regex = "/.*(/login\\?token=.*)";
String toUrl = "/tourl";
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(inputUrl);
if (matcher.find()) {
return toUrl + matcher.group(1);
} else
return null;
}
You can write a test if it works for other expected inputs/outputs if you want to change format and adjust regex:
String inputUrl = "/fromurl/login?token=7c8Q8grW5f2Kz7RP1%2FWsqpVB%2FEluVOGfXQdW4I0v82siR2Ism1D8VCvEmKJr%2BKhHhicwPey0uIiTxN049Be8TNsypf";
String expectedUrl = "/tourl/login?token=7c8Q8grW5f2Kz7RP1%2FWsqpVB%2FEluVOGfXQdW4I0v82siR2Ism1D8VCvEmKJr%2BKhHhicwPey0uIiTxN049Be8TNsypf";
if (expectedUrl.equals(replaceUrl(inputUrl))){
System.out.println("Success");
}

ReplaceAll Method

I want to replace "\" with this "/" in my string.
I am using method replaceAll for this. But it is giving me error.
String filePath = "D:\pbx_u01\apache-tomcat-6.0.32\bin\uploadFiles\win.jpg";
String my_new_str = filePath.replaceAll("\\", "//");
Just use replace.
The method replaceAll takes a regular expression and yours would be malformed.
String filePath = "D:/pbx_u01/apache-tomcat-6.0.32/bin/uploadFiles/win.jpg";
System.out.println(filePath.replace("/", "\\"));
Output
D:\pbx_u01\apache-tomcat-6.0.32\bin\uploadFiles\win.jpg
When you absolutely want to use regex for this, use:
String filePath = "D:\\pbx_u01\\apache-tomcat-6.0.32\\bin\\uploadFiles\\win.jpg";
String my_new_str = filePath.replaceAll("\\\\", "/");
Output of my_new_str would be:
D:/pbx_u01/apache-tomcat-6.0.32/bin/uploadFiles/win.jpg
Just be sure to notice the double backslashes \\ in the source String (you used single ones \ in your question.)
But Mena showed in his answer a much simpler, more readable way to achive the same. (Just adopt the slashes and backslashes)
You are unable because character '//' should be typed only single '/'.
String filePath = "D:\\pbx_u01\\apache-tomcat-6.0.32\\bin\\uploadFiles\\win.jpg"
String my_new_str = filePath.replaceAll("\\", "/");
Above may be fail during execution giving you a PatternSyntaxException, because the first String is a regular expression so you use this,
String filePath = "D:\\pbx_u01\\apache-tomcat-6.0.32\\bin\\uploadFiles\\win.jpg"
String my_new_str = filePath.replaceAll("\\\\", "/");
Check this Demo ideOne

How to extract word from string?

Suppose I have a string:
String message = "you should try http://google.com/";
Now, I want to send "http://google.com/" to a new
String url
What I want to do is:
check if a "word" in the string begins with "http://" and extract that word, where a word is
something that's surrounded by spaces (general english definition of word).
I have no idea how to extract the string, and the best I can do is use startsWith on the string. How to I use startsWith on a word, and extract the word?
Sorry if this is a little bit difficult to explain.
Thanks in advance!
EDIT: Also, what should I do to extract the word from the REGEX operation? And how should I handle it if there is more than 1 url in the string?
Use Pattern & Matcher classes.
String str = "blabla http://www.mywebsite.com blabla";
String regex = "((https?:\\/\\/)?(www.)?(([a-zA-Z0-9-]){2,}\\.){1,4}([a-zA-Z]){2,6}(\\/([a-zA-Z-_/.0-9#:+?%=&;,]*)?)?)";
Matcher m = Pattern.compile(regex).matcher(str);
if (m.find()) {
String url = m.group(); //value "http://www.mywebsite.com"
}
This regex will work for http://..., https://... and even www... URLs. Others regex can be easily found on the net.
You can try this:
String str = "blabla http://www.mywebsite.com blabla";
Matcher m = Pattern.compile("(http://.*)").matcher(str);
if (m.find()) {
String url = (new StringTokenizer(m.group(), " ")).nextToken();
}
The "correct" way to perform this task is to split the String by whitespace -- String#split("\s") -- and then pipe it to the URL constructor. If the string starts with your prefix and a MalformedURLException is thrown it is invalid. The URL class constructor is far better tested and more robust than any solution that you or I could come up with. So, use it, please and don't reinvent the wheel.
You can use Java Regex for this:
The following regex catches any string starting with http:// or https:// till the next whitespace character:
Pattern urlPattern = Pattern.compile("(http(s)?://[.^[\\S]]*)");
Matcher matcher = compile.matcher(myString);
if (matcher.find()) {
String url = matcher.group();
}

Categories

Resources