1

I have a problem with pattern. I need to get value(number and text) after macapp= and after locapp= between 2 words is & how do this

String temp  = "http://sedaword.com/app/fr/main.php?macapp=admin22&locapp=30.330345,59.607153";

Pattern p = Pattern.compile("^.*?macapp=(.+)$&"); //this my problem

Matcher m = p.matcher(temp);

if (m.find()) {

    String macapp = String.valueOf(m.group(1)); //output   admin22
    String locapp= String.valueOf(m.group(2));//output 30.330345,59.607153
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • I think the trick is a *reluctant quantifier*, it will only take up to the first ampersand: `(.+?)&`. And leave out the `$`, I think it causes trouble there. – Ole V.V. Oct 22 '19 at 17:45

3 Answers3

1

You can simply try like this:

String temp  = "http://sedaword.com/app/fr/main.php?macapp=admin22&locapp=30.330345,59.607153";
String[] resultArray = temp.split("macapp=")[1].split("&locapp=");
System.out.println(resultArray[0]); //admin22
System.out.println(resultArray[1]); //30.330345,59.607153
Nongthonbam Tonthoi
  • 12,667
  • 7
  • 37
  • 64
1

You can correct your regular expression in the following way:

String url  = "http://sedaword.com/app/fr/main.php?macapp=admin22&locapp=30.330345,59.607153";

Pattern p = Pattern.compile("^.*\\?macapp=(.+)&locapp=(.+)$");

Matcher m = p.matcher(url);
if (m.find()) {
  String macapp = m.group(1);
  String locapp = m.group(2);
}

But I would suggest you to use some library for this purpose. See also this and this

SternK
  • 11,649
  • 22
  • 32
  • 46
1

Another more generic option is to make use of Java 8's streams and collect all the key value pairs in a map.

String url = "http://sedaword.com/app/fr/main.php?macapp=admin22&locapp=30.330345,59.607153";
url = url.substring( url.indexOf( "main.php" ) + "main.php".length() + 1 ); // substring after main.php

Map<String,String> map = Arrays.stream( url.split( "&" ) ) // split on &
         .map( str -> str.split( "=" ) ) // split on =
         .collect( Collectors.toMap( arr -> arr[ 0 ], arr2 -> arr2[ 1 ] ) ); // collect to map

for ( Map.Entry<String,String> entry : map.entrySet() ) {
    System.out.println( String.format( "Key=%s, value=%s", entry.getKey(), entry.getValue() ) );
}

output is

Key=locapp, value=30.330345,59.607153
Key=macapp, value=admin22
RobOhRob
  • 585
  • 7
  • 17