JS 와 C\#실 현 된 두 정규 교체 기능 예시 분석

2123 단어 JSC#정규 교체
본 고의 실례 는 JS 와 C\#가 실현 한 두 가지 정규 교체 기능 을 다 루 었 다.여러분 께 참고 하도록 공유 하 겠 습 니 다.구체 적 으로 는 다음 과 같 습 니 다.
인 스 턴 스 1 적용:
처리 대기 문자열:str="display=test name=mu display=temp"
요구:display=뒤의 값 을 localhost 로 변경 합 니 다.
JS 처리 방법:

str.replace(/display=\w*/g,"display=localhost");

C\#처리 방법:

Regex reg=new Regex(@"display=\w*");
str=reg.Replace(str,"display=localhost");

응용 실례 2:
처리 대기 문자열:str="display=test name=mu display=temp"
요구:문자열 을 display=localhosttest name=mu display=localhosttemp 으로 변경 합 니 다.
JS 처리 방법:

var reg = /(display=)(\w*)/g;
var result;
while ((result= reg.exec(str))!=null) {
  str= str.replace(result[0], result[1] + "localhost" + result[2]);
}

C\#처리 방법:

/// <summary>
///       
/// </summary>
/// <param name="match">      </param>
/// <returns></returns>
private string Evaluator(Match match)
{
  //(display=)(\w*) Groups                 
  // 0          ,          
  string str =match.Groups[1].Value+"localhost"+ match.Groups[2].Value;
  return str;
}
Regex regex = new Regex(@"(display=)(\w*)");
string result = regex.Replace(str, Evaluator);

마지막 으로 js 의 정규 에 대한 작은 요약 이 있 습 니 다.
문자열
1.정규 표현 식 에/g 가 없 을 때 첫 번 째 일치 하 는 문자열 이나 문자열 그룹 을 되 돌려 줍 니 다.(정규 에 그룹 이 있다 면)
2.정규 표현 식 에/g 가 있 을 때 match 는 모든 문자열 그룹 을 되 돌려 주 고 그룹 을 무시 합 니 다.exec 는 첫 번 째 문자열 이나 문자열 그룹 을 되 돌려 줍 니 다.
PS:여기 서 여러분 께 매우 편리 한 정규 표현 식 도구 2 가 지 를 제공 합 니 다.참고 하 시기 바 랍 니 다.
JavaScript 정규 표현 식 온라인 테스트 도구:
http://tools.jb51.net/regex/javascript
정규 표현 식 온라인 생 성 도구:
http://tools.jb51.net/regex/create_reg
본 고 에서 말 한 것 이 대가 정규 표현 식 학습 에 도움 이 되 기 를 바 랍 니 다.

좋은 웹페이지 즐겨찾기