Regex to find text between string pattren - java

String: [img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]
Result I Want: [img border=0]images/bbcode/sets/misc/bullet_go.png[/img] without /scm/ text.
Issue: Text scm is not static, could be any other text in data.
What I want: Have a look to this string
[img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]
Regex which can fetch a text between ] and images/bbcode/ so the regex will detect the \scm\ text and then can remove this \scm\ from String data and end result will look like
[img border=0]images/bbcode/sets/misc/bullet_go.png[/img]
PS: I am implementing this logic in Java.

you can reach the goal without using regex, too.
since you said that the other parts are static, try this:
String myStr = "[img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]";
myStr = "[img border=0]" + myStr.substring(myStr.indexOf("images"));
System.out.println(myStr);
and the output will be:
[img border=0]images/bbcode/sets/misc/bullet_go.png[/img]

I have captured text between '] and /images..' and replace this text with "". Check the following demo:
String s = "[img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]";
s = s.replaceAll("(?<=])/[^/]+/","");
System.out.println(s);

if [img border=0] dynamic, you can take all except /scm/
some demo
String input = "[img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]";
Pattern p = Pattern.compile("(^.*\\])\\/.*?\\/(.*$)");
Matcher m = p.matcher(input);
if (m.find()) {
String output = m.replaceFirst("$1$2");
System.out.println(output);
}
// -> [img border=0]images/bbcode/sets/misc/bullet_go.png[/img]

I found one more way to solve this same problem
String pattereString = "].*/images";
String maineString = "[img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]";
maineString = maineString.replaceAll(pattereString, "images");
System.out.println(maineString);
Output:
[img border=0]images/bbcode/sets/misc/bullet_go.png[/img]

Related

How to split a string having [] as delimiters in java

I want to remove [ ] braces from the below string-
"[maths=100, english=20]"
I have tried doing it in following ways but in both the trials it is not removing the end ] brace.
Approach 1:
String[] metrics= "[maths=100, english=20]";
String[] value = metrics[1].split("\\[");
String[] finalValue = value[1].split("\\]");
System.out.println(finalValue[0]); // this should give string as maths=100, english=20
Approach 2:
String[] metrics= "[maths=100, english=20]";
String[] value = metrics[1].split("\\[\\]");
System.out.println(finalValue[1]); // this should give string as maths=100, english=20
Can anyone guide me where i am doing it wrong?
Try this code
String metrics= "[maths=100, english=20]";
String[] split = metrics.split("\\[|]");
System.out.println(split[1]);
it prints
"maths=100, english=20"
Or you can simply replace all [ and ] character
String metrics = "[maths=100, english=20]";
metrics = metrics.replace("[", "").replace("]", "");
System.out.println(metrics);
If you simply want to trim and clean your data then you can do a simple check and substring.
String input = ...;
String cleanedInput = input.trim();
if (cleanedInput.startsWith("[") && cleanedInput.endsWith("]")) {
cleanedInput = cleanedInput.substring(1, cleanedInput.length() - 1);
System.out.println(cleanedInput);
}
If you're wanting to match and capture from a larger set of data then you can use RegEx patterns with capture groups to match and capture the data you want.
For parsing a proper document structure though you should try to use a real parser but if you truly are just trying to match and capture some simple data then RegEx will often be ok.
String input = ...;
// RegEx pattern "\[([^\[\]]*)\]" anything inside braces except other braces
Pattern pattern = Pattern.compile("\\[([^\\[\\]]*)\\]");
Matcher matcher = pattern .matcher(input);
while (matcher.find()) {
String data = matcher.group(1);
System.out.println(data);
}
You can simply replace the braces like this:
String s = "[maths=100, english=20]";
s = s.replace("[", "").replace("]", "");
System.out.println(s);

How to fetch a string out of "08-1_2-4_1517614" ie "1517614"

If i have string like 08-1_2-4_1517614 and if i need to fetch the value "1517614" out of this for string manipulation in java
Any help will be much appreciated
String test = " 08-1_2-4_1517614";
String [] tokens = test.split("_");
System.out.println(tokens[tokens.length - 1]);
Or with regex:
String test = " 08-1_2-4_1517614";
System.out.println(test.replaceFirst(".+_", ""));
Or:
System.out.println(test.substring(test.lastIndexOf("_") + 1));
Here is a regex replace option:
String input = "08-1_2-4_1517614";
String output = input.replaceAll("^.*_", "");
A more general regex replace option using a capture group:
String output = input.replaceAll(".*(?<!\\d)(\\d+)$", "$1");
Or we could take a substring:
String output = input.substring(input.lastIndexOf("_") + 1);
Is the pattern always the same?
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#substring-int-int- could be your friend.
"08-1_2-4_1517614".substring(9, "08-1_2-4_1517614".length()) e.g.
Best way to do it, in case you want to resuse other parts of the original String.
String num = "08-1_2-4_1517614";
String[] parts = num.split("_");
String value = parts[parts.length - 1];
System.out.println(value);
The most simple is to use regex to find all the numbers after the final underscore.
Pattern patt = Pattern.compile("[^_]+$");
Matcher matcher = patt.matcher("08-1_2-4_1517614");
if(matcher.find()) {
System.out.println(matcher.group());
}else{
System.out.println("No Match Found");
}
Or use
str.substring(str.lastIndexOf("_") + 1, str.length())
I'd go for the one-liner:
System.out.println(myString.substring(9, 16));

Extract last number after decimal

I am getting a piece of JSON text from a url connection and saving it to a string currently as such:
...//setting up url and connection
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String str = in.readLine();
When I print str, I correctly find the data {"build":{"version_component":"1.0.111"}}
Now I want to extract the 111 from str, but I am having some trouble.
I tried
String afterLastDot = inputLine.substring(inputLine.lastIndexOf(".") + 1);
but I end up with 111"}}
I need a solution that is generic so that if I have String str = {"build":{"version_component":"1.0.111111111"}}; the solution still works and extracts 111111111 (ie, I don't want to hard code extract the last three digits after the decimal point)
If you cannot use a JSON parser then you can this regex based extraction:
String lastNum = str.replaceAll("^.*\\.(\\d+).*", "$1");
RegEx Demo
^.* is greedy match that matches everything until last DOT and 1 or more digits that we put in group #1 to be used in replacement.
Find the start and the end indexes of the String you need and substring(start, end) :
// String str = "{"build":{"version_component":"1.0.111"}};" cannot compile without escaping
String str = "{\"build\":{\"version_component\":\"1.0.111\"}}";
int start = str.lastIndexOf(".")+1;
int end = str.lastIndexOf("\"");
String substring = str.substring(start,end);
just use JSON api
JSONObject obj = new JSONObject(str);
String versionComponent= obj.getJSONObject("build").getString("version_component");
Then just split and take the last element
versionComponent.split("\\.")[2];
Please, your can try the following code :
...
int index = inputLine.lastIndexOf(".")+1 ;
String afterLastDot = inputLine.substring(index, index+3);
With Regular Expressions (Rexp),
You can solve your problem like this ;
Pattern pattern = Pattern.compile("111") ;
Matcher matcher = pattern.matcher(str) ;
while(matcher.find()){
System.out.println(matcher.start()+" "+matcher.end());
System.out.println(str.substring(matcher.start(), matcher.end()));
}

how to read string upto certain comma with java

i need to read a file upto certain comma,for example;
String s=hii,lol,wow,and,finally
need output as hii,lol,wow,and
Dont want last comma followed with characters
As my code is reading last comma string
Example:iam getting my code out put as: finally
Below is my code
please guide me
File file =new File("C:/Users/xyz.txt");
FileInputStream inputStream = new FileInputStream(file);
String filke = IOUtils.toString(inputStream);
String[] pieces = filke.split("(?=,)");
String answer = Arrays.stream(pieces).skip(pieces.length - 1).collect(Collectors.joining());
String www=answer.substring(1);
System.out.format("Answer = \"%s\"%n", www);
You don't necessarily need to use regex for this. Just get the index of the last ',' and get the substring from 0 to that index:
String answer = "hii,lol,wow,and,finally";
String www = answer.substring(0, answer.lastIndexOf(','));
System.out.println(www); // prints hii,lol,wow,and
String in Java has a method called lastIndexOf(String str). That might come in handy for you.
Say your input is String s = "hii,lol,wow,and,finally";
You can do a String operation like:
String s = "hii,lol,wow,and,finally";
s = s.substring(0, s.lastIndexOf(","));
This gives you the output: hii,lol,wow,and
If you want to use java 8 stream to do it for you maybe try filter ?
String answer = Arrays.stream(pieces).filter(p -> !Objects.equals(p, pieces[pieces.length-1])).collect(Collectors.joining());
this will print Answer = "hii,lol,wow,and"
To have stricly regex you can use the Pattern.compile and Matcher
Pattern.compile("\w+(?=,)");
Matcher matcher = pattern.matcher(filke);
while (matcher.find()) {
System.out.println(matcher.group(1) + ","); // regex not good enough, maybe someone can edit it to include , (comma)
}
Will match hii, lol, wow, and,
See the regex example here https://regex101.com/r/1iZDjg/1

How to Extract text from given string?

I want to extract a perticular image path string from a given string .
The String is http:\localhost:9090\SpringMVC\images\integration-icon.png
Now i want to get only the path after images like
\images\integration-icon.png
i tried this
Pattern pattern = Pattern.compile("SpringMVC");
Matcher matcher = pattern.matcher(str);
System.out.println("Checking");
if (matcher.find()) {
System.out.println(matcher.group(1));
}
how can i get ?
String filename = filepath.substring(filepath.lastIndexOf("\\") + 1);
or (haven't tried and looks somewhat odd)
String filename = filepath.substring(filepath.lastIndexOf("\\", "images\\".length()) + 1);
String string = "http:\localhost:9090\ZenoBusinessStore\images\integration-icon.png";
int index = string.indexOf("images\\");
String output = string.substring(index);
String text = "http:\localhost:9090\SpringMVC\images\integration-icon.png"
String subText = text.subString(text.indexOf("\images"), text.length());
System.out.println(subText);
String in = "http:\\localhost:9090\\ZenoBusinessStore\\images\\integration-icon.png";
String op = in.replace("http:\\localhost:9090\\ZenoBusinessStore", "");
System.out.println(op);
ZenoBusinessStore must be the name of your project which is constant.
Now split the string
String s = "http:\localhost:9090\ZenoBusinessStore\images\integration-icon.png";
String ary = s.split("ZenoBusinessStore");
Now the 2nd element of the array is your image path.
System.out.println(ary[1]);
Use '\\'. It's because backslash is used in escape sequence like '\n'. With a single \ the compiler have no way to know.

Categories