Advertisement
m_naish

regex - android

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