Use regex to replace a specific pattern - java

From a given string, am trying to replace a pattern such as "sometext.othertext.lasttext" with "lasttext". Is this possible in Java with Regex replace? If yes, how? Thanks in advance.
I tried
"hellow.world".replaceAll("(.*)\\.(.*)", "$2")
which results in world. But, I want to replace any such arbitrary sequence. For instance com.google.code should be replace with code and com.facebook should be replaced with facebook.
Just to add, a test input is:
if (com.google.code) then
and the test output should be:
if (code) then
Thanks.

I believe this is what you are looking for, if you're trying to avoid String methods. It can be made more succinct, but I'm hoping this will give you a better understanding.
As others suggested, String methods are cleaner.
class Split {
public static void main (String[] args) {
String inputString = "if (com.google.code) then";
Pattern p=Pattern.compile("((?<=\\()[^}]*(?=\\)))"); // Find text within parenthesis
Pattern p2 = Pattern.compile("(\\w+)(\\))"); // Find last portion of text between . and )
Matcher m = p.matcher(inputString);
Matcher m2 = p2.matcher(inputString);
String in2 = "";
if (m2.find())
in2=m2.group(1); // else ... error checking
inputString = m.replaceAll(in2); // do whatcha need to do
}
}
If the parenthesis aren't the concern, use this.
class Split {
public static void main (String[] args) {
String in = "if (com.google.code) then";
Pattern p = Pattern.compile("(\\w+)(\\))");
Matcher m = p.matcher(in);
if(m.find())
in = m.group(1);
System.out.println(in); // or whatever
}
}

Use:
str.replaceAll(".*\\.(\\w+)$", "$1")
Explanation here

Related

How get numeric between two character with regex java?

I have the string as follows :
SUB8&20.000,-&succes&09/12/18SUB12&100.000,-&failed&07/12/18SUB16&40.000,-&succes&09/12/18
I want to get a string "8&20.000","16&40.000" between SUB and ,-&succes
I want to get succes data how to get the string using java regex ?
Use this regex,
SUB([^,]*),-&succes
Java code,
public static void main(String[] args) {
String s = "SUB8&20.000,-&succes&09/12/18SUB12&100.000,-&failed&07/12/18SUB16&40.000,-&succes&09/12/18";
Pattern p = Pattern.compile("SUB([^,]*),-&succes");
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group(1));
}
}
Prints,
8&20.000
16&40.000
Check here
You could use the pattern SUB[^S]+&success[^S]+ and choose the one you want after that.
The two match would be SUB8&20.000,-&succes&09/12/18 and SUB16&40.000,-&succes&09/12/18.
Once you have chosen you can strip away the unwanted stuff with [0-9]+&[0-9.]+.
I don`t know if I am answering your question properly or not. But this regex will give exact string that you are looking for.
(?<=SUB)([^,]*)(?=,-&succes)
https://regex101.com/r/RLFXNf/1

Print out the last match of a regex

I have this code:
String responseData = "http://xxxxx-f.frehd.net/i/world/open/20150426/1370235-005A/EPISOD-1370235-005A-016f1729028090bf_,892,144,252,360,540,1584,2700,.mp4.csmil/.m3u8";
"http://xxxxx-f.frehd.net/i/world/open/20150426/1370235-005A/EPISOD-1370235-005A-016f1729028090bf_,892,144,252,360,540,1584,2700,.mp4.csmil/.m3u8";
String pattern = ^(https://.*\.54325)$;
Pattern pr = Pattern.compile(pattern);
Matcher math = pr.matcher(responseData);
if (math.find()) {
// print the url
}
else {
System.out.println("No Math");
}
I want to print out the last string that starts with http and ends with .m3u8. How do I do this? I'm stuck. All help is appreciated.
The problem I have now is that when I find a math and what to print out the string, I get everything from responseData.
In case you need to get some substring at the end that is preceded by similar substrings, you need to make sure the regex engine has already consumed as many characters before your required match as possible.
Also, you have a ^ in your pattern that means beginning of a string. Thus, it starts matching from the very beginning.
You can achieve what you want with just lastIndexOf and substring:
System.out.println(str.substring(str.lastIndexOf("http://")));
Or, if you need a regex, you'll need to use
String pattern = ".*(http://.*?\\.m3u8)$";
and use math.group(1) to print the value.
Sample code:
import java.util.regex.*;
public class HelloWorld{
public static void main(String []args){
String str = "http://xxxxx-f.akamaihd.net/i/world/open/20150426/1370235-005A/EPISOD-1370235-005A-016f1729028090bf_,892,144,252,360,540,1584,2700,.mp4.csmil/index_0_av.m3u8" +
"EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2795000,RESOLUTION=1280x720,CODECS=avc1.64001f, mp4a.40.2" +
"http://xxxxx-f.akamaihd.net/i/world/open/20150426/1370235-005A/EPISOD-1370235-005A-016f1729028090bf_,892,144,252,360,540,1584,2700,.mp4.csmil/index_6_av.m3u8";
String rx = ".*(http://.*?\\.m3u8)$";
Pattern ptrn = Pattern.compile(rx);
Matcher m = ptrn.matcher(str);
while (m.find()) {
System.out.println(m.group(1));
}
}
}
Output:
http://xxxxx-f.akamaihd.net/i/world/open/20150426/1370235-005A/EPISOD-1370235-005A-016f1729028090bf_,892,144,252,360,540,1584,2700,.mp4.csmil/index_6_av.m3u8
Also tested on RegexPlanet

I am trying to extract text using regex but it is not working

I am trying to extract text using regex but it is not working. Although my regex work fine on regex validators.
public class HelloWorld {
public static void main(String []args){
String PATTERN1 = "F\\{([\\w\\s&]*)\\}";
String PATTERN2 = "{([\\w\\s&]*)\\}";
String src = "F{403}#{Title1}";
List<String> fvalues = Arrays.asList(src.split("#"));
System.out.println(fieldExtract(fvalues.get(0), PATTERN1));
System.out.println(fieldExtract(fvalues.get(1), PATTERN2));
}
private static String fieldExtract(String src, String ptrn) {
System.out.println(src);
System.out.println(ptrn);
Pattern pattern = Pattern.compile(ptrn);
Matcher matcher = pattern.matcher(src);
return matcher.group(1);
}
}
Why not use:
Pattern regex = Pattern.compile("F\\{([\\d\\s&]*)\\}#\\{([\\s\\w&]*)\\}");
To get both ?
This way the number will be in group 1 and the title in group 2.
Another thing if you're going to compile the regex (which can be helpful to performance) at least make the regex object static so that it doesn't get compiled each time you call the function (which kind of misses the whole pre-compilation point :) )
Basic demo here.
First problem:
String PATTERN2 = "\\{([\\w\\s&]*)\\}"; // quote '{'
Second problem:
Matcher matcher = pattern.matcher(src);
if( matcher.matches() ){
return matcher.group(1);
} else ...
The Matcher must be asked to plough the field, otherwise you can't harvest the results.

Replace pattern Java

I am making a program that allows the user to set variables and then use them in their messages such as %variable1% and I need a way of detecting the pattern which indicates a variable (%STRING%) . I am aware that I can use regex to find the patterns but am unsure how to use it to replace text.
I can also see a problem arising when using multiple variables in a single string as it may detect the space between 2 variables as a third variable
e.g. %var1%<-text that may be detected as a variable->%var2%, would this happen and is there any way to stop it?
Thanks.
A non-greedy regex would be helpful in extracting the variables which are within the 2 distinct % signs:
Pattern regex = Pattern.compile("\\%.*?\\%");
In this case if your String is %variable1%mndhokajg%variable2%" it should print
%variable1%
%variable2%
If your String is %variable1%variable2% it should print
%variable1%
%variable1%%variable2% should print
%variable1%
%variable2%
You can now manipulate/use the extracted variables for your purpose:
Code:
public static void main(String[] args) {
try {
String tag = "%variable1%%variable2%";
Pattern regex = Pattern.compile("\\%.*?\\%");
Matcher regexMatcher = regex.matcher(tag);
while (regexMatcher.find()) {
System.out.println(regexMatcher.group());
}
} catch (Exception e) {
e.printStackTrace();
}
}
Try playing around with different Strings, there can be invalid scenarios with % as part of the String but your requirement doesn't seem to be that stringent.
Oracle's tutorial on the Pattern and Matcher classes should get you started. Here is an example from the tutorial that you may be interested in:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class ReplaceDemo {
private static String REGEX = "dog";
private static String INPUT =
"The dog says meow. All dogs say meow.";
private static String REPLACE = "cat";
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
// get a matcher object
Matcher m = p.matcher(INPUT);
INPUT = m.replaceAll(REPLACE);
System.out.println(INPUT);
}
}
Your second problem shouldn't happen if you use regex properly.
You can use this method for variable detection and their replacements from a passed HashMap:
// regex to detect variables
private final Pattern varRE = Pattern.compile("%([^%]+)%");
public String varReplace(String input, Map<String, String> dictionary) {
Matcher matcher = varRE.matcher( input );
// StringBuffer to hold replaced input
StringBuffer buf = new StringBuffer();
while (matcher.find()) {
// get variable's value from dictionary
String value = dictionary.get(matcher.get(1));
// if found replace the variable's value in input string
if (value != null)
matcher.appendReplacement(buf, value);
}
matcher.appendTail(buf);
return buf.toString();
}

Regex and String Manipulation Techniques

Given that an input String may be specified as follows:
read(xpath(‘...’)) or
xpath(‘...’) or
...
Where ... just holds some xpath expression, for example,/comment/text
All I really want is the xpath expression; what would be an efficient way to in general extract this value given the three possible valid patterns that could be specified.
Also, I am implementing this in Java.
Here is the basic example, it matches xpath part in both of your string examples:
import java.util.regex.*;
class Untitled {
public static void main(String[] args) {
String input = "read(xpath('...'))";
String result = null;
Pattern regex = Pattern.compile("xpath\\(\'(.*?)\'\\)");
Matcher matcher = regex.matcher(input);
if (matcher.find()) {
result = matcher.group(1);
}
System.out.println(result);
}
}
It would have helped you posted some code but you can use String Split. Please refer to http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#split%28java.lang.String%29
If you are sure to have xpath('') , then you can use xpath(' as your regex and strip the string and gather the data inside it until it hits another ' (apostrophe).
I hope this gives you an idea.

Categories