Regular Expression Search On String - java

I am having great issues searching a string for particular parameters that are needed in my application, I am under the assumption that the only real way to do this is using regular expressions however they are giving me a huge headache! I don't usually write them myself but get them off other websites however what i need isn't simple enough to be included :(
Here is the string:
10 50 u E2U+pstn:tel "!^(.*)$!tel:\\1;spn=42180;mcc=234;mnc=33!" .
I need to extract the spn, mcc, and the mnc from this string. Unfortunately the api i call changes the location of these on the string for some requests which makes indexing the string difficult. I really need to list what i need to grab the spn= for example then follow off and read the number but everything i try never works.

I wouldn't use regex but simply splitting :
String[] tokens = str.split(";");
for (int i=0; i<tokens.length; i++) {
if (tokens[i].startsWith("spn=")) {
spn = Integer.parseInt(tokens[i].substring("spn=".length()));
}
}
Of course you could objectify this a little, or use constants for "spn=".

A solution using Pattern and Matcher:
String s = "10 50 u E2U+pstn:tel \"!^(.*)$!tel:\\\\1;spn=42180;mcc=234;mnc=33!\"";
Pattern p = Pattern.compile("^.*spn=([0-9]+);mcc=([0-9]*);mnc=([0-9]*)!.*$");
Matcher matcher = p.matcher(s);
matcher.matches(); // true
String spn = matcher.group(1); // 42180
String mcc = matcher.group(2); // 234
String mnc = matcher.group(3); // 33
Edit: You can use named-capturing groups, too:
Pattern p =
Pattern.compile("^.*spn=(?<spn>[0-9]+);mcc=(?<mcc>[0-9]*);mnc=(?<mnc>[0-9]*)!.*$");
Matcher matcher = p.matcher(s);
matcher.matches(); // true
String spn = matcher.group("spn");
String mcc = matcher.group("mcc");
String mnc = matcher.group("mnc");

Related

Regex capture group within if statement in Java

I'm facing a stupid problem... I know how to use Pattern and Matcher objects to capture a group in Java.
However, I cannot find a way to use them with an if statement where each choice depends on a match (simple example to illustrate the question, in reality, it's more complicated) :
String input="A=B";
String output="";
if (input.matches("#.*")) {
output="comment";
} else if (input.matches("A=(\\w+)")) {
output="value of key A is ..."; //how to get the content of capturing group?
} else {
output="unknown";
}
Should I create a Matcher for each possible test?!
Yes, you should.
Here is the example.
Pattern p = Pattern.compile("Phone: (\\d{9})");
String str = "Phone: 123456789";
Matcher m = p.matcher(str);
if (m.find()) {
String g = m.group(1); // g should hold 123456789
}

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");
}

Regex: how to extract a JSESSIONID cookie value from cookie string?

I might receive the following cookie string.
hello=world;JSESSIONID=sdsfsf;Path=/ei
I need to extract the value of JSESSIONID
I use the following pattern but it doesn't seem to work. However https://regex101.com shows it's correct.
Pattern PATTERN_JSESSIONID = Pattern.compile(".*JSESSIONID=(?<target>[^;\\n]*)");
You can reach your goal with a simpler approach using regex (^|;)JSESSIONID=(.*);. Here is the demo on Regex101 (you have forgotten to link the regular expression using the save button). Take a look on the following code. You have to extract the matched values using the class Matcher:
String cookie = "hello=world;JSESSIONID=sdsfsf;Path=/ei";
Pattern PATTERN_JSESSIONID = Pattern.compile("(^|;)JSESSIONID=(.*);");
Matcher m = PATTERN_JSESSIONID.matcher(cookie);
if (m.find()) {
System.out.println(m.group(0));
}
Output value:
sdsfsf
Of course the result depends on the all of possible variations of the input text. The snippet above will work in every case the value is between JSESSIONID and ; characters.
You can try below regex:
JSESSIONID=([^;]+)
regex explanation
String cookies = "hello=world;JSESSIONID=sdsfsf;Path=/ei;submit=true";
Pattern pat = Pattern.compile("\\bJSESSIONID=([^;]+)");
Matcher matcher = pat.matcher(cookies);
boolean found = matcher.find();
System.out.println("Sesssion ID: " + (found ? matcher.group(1): "not found"));
DEMO
You can even get what you aiming for with Splitting and Replacing the string aswell, below I am sharing which is working for me.
String s = "hello=world;JSESSIONID=sdsfsf;Path=/ei";
List<String> sarray = Arrays.asList(s.split(";"));
String filterStr = sarray.get(sarray.indexOf("JSESSIONID=sdsfsf"));
System.out.println(filterStr.replace("JSESSIONID=", ""));

JAVA Get text from String

Hi I get this String from server :
id_not="autoincrement"; id_obj="-"; id_tr="-"; id_pgo="-"; typ_not=""; tresc="Nie wystawił"; datetime="-"; lon="-"; lat="-";
I need to create a new String e.x String word and send a value which I get from String tresc="Nie wystawił"
Like #Jan suggest in comment you can use regex for example :
String str = "id_not=\"autoincrement\"; id_obj=\"-\"; id_tr=\"-\"; id_pgo=\"-\"; typ_not=\"\"; tresc=\"Nie wystawił\"; datetime=\"-\"; lon=\"-\"; lat=\"-\";";
Pattern p = Pattern.compile("tresc(.*?);");
Matcher m = p.matcher(str);
if (m.find()) {
System.out.println(m.group());
}
Output
tresc="Nie wystawił";
If you want to get only the value of tresc you can use :
Pattern p = Pattern.compile("tresc=\"(.*?)\";");
Matcher m = p.matcher(str);
if (m.find()) {
System.out.println(m.group(1));
}
Output
Nie wystawił
Something along the lines of
Pattern p = Pattern.compile("tresc=\"([^\"]+)\");
Matcher m = p.matcher(stringFromServer);
if(m.find()) {
String whatYouWereLookingfor = m.group(1);
}
should to the trick. JSON parsing might be much better in the long run if you need additional values
Your question is unclear but i think you get a string from server and from that string you want the string/value for tresc. You can first search for tresc in the string you get. like:
serverString.substring(serverString.indexOf("tresc") + x , serverString.length());
Here replace x with 'how much further you want to pick characters.
Read on substring and delimiters
As values are separated by semicolon so annother solution could be:
int delimiter = serverstring.indexOf(";");
//in string thus giving you the index of where it is in the string
// Now delimiter can be -1, if lets say the string had no ";" at all in it i.e. no ";" is not found.
//check and account for it.
if (delimiter != -1)
String subString= serverstring.substring(5 , iend);
Here 5 means tresc is on number five in string, so it will five you tresc part.
You can then use it anyway you want.

How can i derive specific data from the string?

I have the following string and i want to derive the number (104321) from the a href tag . How can i derive this number .
Hello this is testing string Ap<img src=\"Image Url" width=\"222\" height=\"149\"/><br/><br/>test\u00e4n p\u00e4\u00e4ll\u00e4 test, test\u00e4, test?
i want the final output to be like this.
String[] strExample= {"testing", "104321","test\u00e4n p\u00e4\u00e4ll\u00e4 test, test\u00e4, test?"};
Any help is appreciated.
You could try a simple Pattern matcher with the regexp:
String THE_PATTERN = "<a\\s+href\\s*=\\s*\"/([a-zA-Z]+)/([0-9]+)";
Matcher m = Pattern.compile(THE_PATTERN).matcher(THE_INPUT_STRING);
String[] results = new String[2];
if (m.find()) {
results[0] = m.group(1);
results[1] = m.group(2);
}
Haven't tried it though, so there could be small/easy-to-fix errors.
For that single case
String[] strExample = str.split("^.+?\\\"/|\\\\\">.+<br/>|/");
will work. It will break if the string you want to parse changes much though. Some more examples would probably be in place if there are more patterns you need to account for.

Categories

Resources