熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

JAVA語言編程中如何使用表達式

2022-06-13   來源: Java核心技術 

  JAVA 正則表達式涉及的三個類:

  StringPatternMatcher

  Pattern是要匹配的模式Matcher是匹配的結果

  例如:Pattern p = plie([az]{});

  Matcher m = pmather(abc);

  要想在正則表達式中匹配一個反斜線用四個反斜線表示: \\matches(\\\\);

  匹配空白行 \nmatches(^[\\s&&[^\\n]]*\\n$);

  找出匹配結果在整個字符串的開始位置和結束位置

  Pattern p = plie(\\d{});

  String a = ;

  Matcher m = pmatcher(s);

  mmatches() // 匹配整個字符串所以這裡是false;

  mreset();

  while(mfind()) // 找一個和這個模式所匹配的子串

  {

  Systemoutprintln(mstart() + To + mend());

  }

  將匹配到的java都轉換成大寫的

  Pattern p = plie(java PatternCASE_INSENSITIVE);

  Matcher m = pmatcher(java Java JaVa IloveJava You HateJaVA);

  mreplaceAll(JAVA);

  將匹配偶數個轉換為大寫奇數個轉換為小寫

  package zxtest;

  import javautilregexMatcher;

  import javautilregexPattern;

  public class TestPattern

  {

  public static void main(String[] args)

  {

  StringBuffer newString = new StringBuffer();

  String isPatternString = java Java JaVa IloveJava You HateJaVA;

  Pattern p = pile(java PatternCASE_INSENSITIVE);

  Matcher m = pmatcher(isPatternString);

  int i = ;

  while(mfind())

  {

  i++;

  if (i % == )

  {

  mappendReplacement(newString java);

  }

  else

  {

  mappendReplacement(newString JAVA);

  }

  }

  mappendTail(newString);

  Systemoutprintln(newString);

  }

  }

  輸出結果:JAVA java JAVA Ilovejava You HateJAVA

  Java正則表達式分組:

  private static void testGroup()

  {

  String s = afdsafijiikfsdfaf;

  Pattern p = pile((\\d{})([az]{})); // 組:(\\d{}) 組:([az]{})

  Matcher m = pmatcher(s);

  while(mfind())

  {

  Systemoutprintln(Group: + mgroup() + Group: + mgroup() + Group: + mgroup());

  }

  }

  輸出結果:

  Group: afdsaf Group: Group: afdsaf

  Group: ijii Group: Group: ijii

  Group: k Group: Group: k

  Group: fsdfaf Group: Group: fsdfaf


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26661.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.