Advertisement
amjadArabia

RegExr

Nov 14th, 2017
390
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.77 KB | None | 0 0
  1. import android.support.v7.app.AppCompatActivity;
  2. import android.os.Bundle;
  3. import android.util.Log;
  4.  
  5. import java.util.regex.Matcher;
  6. import java.util.regex.Pattern;
  7.  
  8. public class MainActivity extends AppCompatActivity {
  9.  
  10.     private static final String TAG="REGEX";
  11.  
  12.     private final String REGEX="\\boleg.\\b";
  13.     private final String INPUT="oleg oleg2 olegy olega aleg aoleg";
  14.     private final String REPLEACE = "Bar ";
  15.     private final String REGEX_OLEG="Oleg";
  16.     private final String INPUT2="Oleg bought a new Volvo and Oleg bought a villa and a viola";
  17.     private final String REPLEACE_TO_TRUTH="Anna";
  18.  
  19.  
  20.  
  21.     @Override
  22.     protected void onCreate(Bundle savedInstanceState) {
  23.         super.onCreate(savedInstanceState);
  24.         setContentView(R.layout.activity_main);
  25.         //regex1();
  26.         regex2();
  27.  
  28.         //regex3();
  29.     }
  30.  
  31.     private void regex1() //find
  32.     {
  33.         Pattern p = Pattern.compile(REGEX);
  34.         Matcher m= p.matcher(INPUT);
  35.  
  36.         int counter=0;
  37.         while (m.find())
  38.         {
  39.             counter+=1;
  40.         }
  41.         Log.e(TAG, "regex1: oleg was found "+counter+" times");
  42.     }
  43.  
  44.     private void regex2() //replace
  45.     {
  46.         Pattern p = Pattern.compile(REGEX);
  47.         Matcher m = p.matcher(INPUT);
  48.         String input = m.replaceAll(REPLEACE);
  49.  
  50.         Log.e(TAG, "regex2: "+input );
  51.     }
  52.  
  53.     private void regex3()
  54.     {
  55.         Pattern p = Pattern.compile(REGEX_OLEG);
  56.         Matcher m = p.matcher(INPUT2);
  57.         int counter=0;
  58.  
  59.         while (m.find())
  60.         {
  61.             counter+=1;
  62.         }
  63.         Log.e(TAG, "regex3: need to replace oleg "+counter+" Times");
  64.  
  65.         String theTruth=m.replaceAll(REPLEACE_TO_TRUTH);
  66.  
  67.  
  68.         Log.e(TAG, "regex3: "+theTruth);
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement