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
Related
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
I need to remove some specific "special" characters and replace them with empty string if they show up.
I am currently having a problem with the regex, probably with the Java escaping. I can't put them all together, it just doesn't work, I tried a lot! T_T
Currently I am doing it one by one which is kinda silly, but for now at least it works, like that :
public static String filterSpecialCharacters(String string) {
string = string.replaceAll("-", "");
string = string.replaceAll("\\[", "");
string = string.replaceAll("\\]", "");
string = string.replaceAll("\\^", "");
string = string.replaceAll("/", "");
string = string.replaceAll(",", "");
string = string.replaceAll("'", "");
string = string.replaceAll("\\*", "");
string = string.replaceAll(":", "");
string = string.replaceAll("\\.", "");
string = string.replaceAll("!", "");
string = string.replaceAll(">", "");
string = string.replaceAll("<", "");
string = string.replaceAll("~", "");
string = string.replaceAll("#", "");
string = string.replaceAll("#", "");
string = string.replaceAll("$", "");
string = string.replaceAll("%", "");
string = string.replaceAll("\\+", "");
string = string.replaceAll("=", "");
string = string.replaceAll("\\?", "");
string = string.replaceAll("|", "");
string = string.replaceAll("\"", "");
string = string.replaceAll("\\\\", "");
string = string.replaceAll("\\)", "");
string = string.replaceAll("\\(", "");
return string;
}
Those are all the character I need to remove:
- [ ] ^ / , ' * : . ! > < ~ # # $ % + = ? | " \ ) (
I am clearly missing something, I can't figure out how to put it all in one line. Help?
Your code does not work in fact because .replaceAll("$", "") replaces an end of string with empty string. To replace a literal $, you need to escape it. Same issue is with the pipe symbol removal.
All you need to do is to put the characters you need to replace into a character class and apply the + quantifier for better performance, like this:
string = string.replaceAll("[-\\[\\]^/,'*:.!><~##$%+=?|\"\\\\()]+", "");
Note that inside a character class, most "special regex metacharacters" lose their special status, you only have to escape [, ], \, a hyphen (if it is not at the start/end of the character class), and a ^ (if it is the first symbol in the "positive" character class).
DEMO:
String s = "-[]^/,'*:.!><~##$%+=?|\"\\()TEXT";
s = s.replaceAll("[-\\[\\]^/,'*:.!><~##$%+=?|\"\\\\()]+", "");
System.out.println(s); // => TEXT
Use these codes
String REGEX = "YOUR_REGEX";
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(yourString);
yourString = m.replaceAll("");
UPDATE :
Your REGEX looks something like
String REGEX = "-|\\[|\\]|\\^|\\/|,|'|\\*|\\:|\\.|!|>|<|\\~|#|#|\\$|%|\\+|=\\?|\\||\\\\|\\\\\\\\|\\)|\\(";
SAPMLE :
String yourString = "#My (name) -is #someth\ing"";
//Use Above codes
Log.d("yourString",yourString);
OUTPUT
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();
}
EDIT :
Goal : http://localhost:8080/api/upload/form/test/test
Is it possible to have some thing like `{a-b, A-B..0-9}` kind of pattern and match them and replace with value.
i have following string
http://localhost:8080/api/upload/form/{uploadType}/{uploadName}
there can be any no of strings like {uploadType}/{uploadName}.
how to replace them with some values in java?
[Edited] Apparently you don't know what substitutions you'll be looking for, or don't have a reasonable finite Map of them. In this case:
Pattern SUBST_Patt = Pattern.compile("\\{(\\w+)\\}");
StringBuilder sb = new StringBuilder( template);
Matcher m = SUBST_Patt.matcher( sb);
int index = 0;
while (m.find( index)) {
String subst = m.group( 1);
index = m.start();
//
String replacement = "replacement"; // .. lookup Subst -> Replacement here
sb.replace( index, m.end(), replacement);
index = index + replacement.length();
}
Look, I'm really expecting a +1 now.
[Simpler approach] String.replace() is a 'simple replace' & easy to use for your purposes; if you want regexes you can use String.replaceAll().
For multiple dynamic replacements:
public String substituteStr (String template, Map<String,String> substs) {
String result = template;
for (Map.Entry<String,String> subst : substs.entrySet()) {
String pattern = "{"+subst.getKey()+"}";
result = result.replace( pattern, subst.getValue());
}
return result;
}
That's the quick & easy approach, to start with.
You can use the replace method in the following way:
String s = "http://localhost:8080/api/upload/form/{uploadType}/{uploadName}";
String typevalue = "typeValue";
String nameValue = "nameValue";
s = s.replace("{uploadType}",value).replace("{uploadName}",nameValue);
You can take the string that start from {uploadType} till the end.
Then you can split that string using "split" into string array.
Were the first cell(0) is the type and 1 is the name.
Solution 1 :
String uploadName = "xyz";
String url = "http://localhost:8080/api/upload/form/" + uploadName;
Solution 2:
String uploadName = "xyz";
String url = "http://localhost:8080/api/upload/form/{uploadName}";
url.replace("{uploadName}",uploadName );
Solution 3:
String uploadName = "xyz";
String url = String.format("http://localhost:8080/api/upload/form/ %s ", uploadName);
String s = "http://localhost:8080/api/upload/form/{uploadType}/{uploadName}";
String result = s.replace("uploadType", "UploadedType").replace("uploadName","UploadedName");
EDIT: Try this:
String r = s.substring(0 , s.indexOf("{")) + "replacement";
The UriBuilder does exactly what you need:
UriBuilder.fromPath("http://localhost:8080/api/upload/form/{uploadType}/{uploadName}").build("foo", "bar");
Results in:
http://localhost:8080/api/upload/form/foo/bar
This is a part of a string
test="some text" test2="othertext"
It contains a lot more of similar text with same formating. Each "statment" is separate by empty space
How to search by name(test, test2) and replace its values(stuff between "")?
in java
I dont know if its clear enough but i dont know how else to explain it
I want to search for "test" and replace its content with something else
replace
test="some text" test2="othertext"
with something else
Edit:
This is a content of a file
test="some text" test2="othertext"
I read content of that file in a string
Now i want to replace some text with something else
some text is not static it can be anything
You can use the replace() method of String, which comes in 3 types and 4 variants:
revStr.replace(oldChar, newChar)
revStr.replace(target, replacement)
revStr.replaceAll(regex, replacement)
revStr.replaceFirst(regex, replacement)
Eg:
String myString = "Here is the home of the home of the Stars";
myString = myString.replace("home","heaven");
///////////////////// Edited Part //////////////////////////////////////
String s = "The quick brown fox test =\"jumped over\" the \"lazy\" dog";
String lastStr = new String();
String t = new String();
Pattern pat = Pattern.compile("test\\s*=\\s*\".*\"");
Matcher mat = pat.matcher(s);
while (mat.find()) {
// arL.add(mat.group());
lastStr = mat.group();
}
Pattern pat1 = Pattern.compile("\".*\"");
Matcher mat1 = pat1.matcher(lastStr);
while (mat1.find()) {
t = mat.replaceAll("test=" + "\"Hello\"");
}
System.out.println(t);
So you want to replace every instance of "test" with something else?
Let's say the string name is myString:
myString = myString.replace("test","something else");
Is this what you are looking to do?
I think you are asking that you fetch data from file in the form of string,
lets suppose, your string is,
String s = "My name="sahil" and my company="microsoft", also i live in
country="india"".
Now you want to replace "sahil" with "mahajan" and "microsoft" with "google".
I have tried experimenting with the string methods to implement this functionality, but didnt find a relavent result. But i could provide you with some methods. You could use regionMatches, indexOf("name=""). But these functions will help you in finding where sahil(suppose) is located. but the replcae function here is difficult to work, because it replaces character sequence, for which you should know the exact character sequence.
Now you might try experimenting with the string methods. It could help.
I haven't tested this, but it should work:
String mFileContents;
private void replaceValue(String name, String newValue) {
int nameIndex = mFileContents.indexOf(name);
int equalSignIndex = mFileContents.indexOf("=", nameIndex);
int oldValueIndex = equalSignIndex + 2;
int oldValueLength = mFileContents.indexOf("\"", oldValueIndex);
String oldValue = mFileContents.substring(oldValueIndex, oldValueLength);
String firstHalf = mFileContents.substring(0, oldValueIndex -1);
String secondHalf = mFileContents.substring(oldValueIndex);
secondHalf.replaceFirst(oldValue, newValue);
mFileContents = firstHalf + secondHalf;
}
String a = "some text";
a = a.replace("text", "inserted value");
System.out.print(a);
Try this