2010-03-11 7 views
1

문자열을 바꾸려면 정규 표현식이 필요합니다. 이 하나정규 표현식 대체 텍스트

<span class=\"Translation\" lang=\"ThisLanguage\"> 

:

이 문자열의 많은 언어가
<span class=\"Translation\" lang=\"ThisLanguage\" onDblClick=\"window.external.MyFunction(ThisLanguage)\"> 

, 각각에 포함 된 다른 "ThisLanguage"

사람이 그것을 할 수있는 방법을 알고?

전 C# .NET을

감사 일하고 있어요!

답변

1

약간 장황하지만, (예를 들어, DOM) 가장 사소한 예를 제외한 모든 들어 차라리 HTML 파서를 통해 HTML을 구문 분석하고 적절한 API를 통해이를 조작!

// using System.Text.RegularExpressions; 

/// <summary> 
/// Regular expression built for C# on: Thu, Mar 11, 2010, 04:37:21 PM 
/// Using Expresso Version: 3.0.2766, http://www.ultrapico.com 
/// 
/// A description of the regular expression: 
/// 
/// <span.*?class=" 
///  <span 
///  Any character, any number of repetitions, as few as possible 
///  class=" 
/// [1]: A numbered capture group. [.*?] 
///  Any character, any number of repetitions, as few as possible 
/// ".*?lang=" 
///  " 
///  Any character, any number of repetitions, as few as possible 
///  lang=" 
/// [2]: A numbered capture group. [.*?] 
///  Any character, any number of repetitions, as few as possible 
/// "> 
///  "> 
/// 
/// 
/// </summary> 
public static Regex regex = new Regex(
     "<span.*?class=\"(.*?)\".*?lang=\"(.*?)\">", 
    RegexOptions.IgnoreCase 
    | RegexOptions.CultureInvariant 
    | RegexOptions.IgnorePatternWhitespace 
    | RegexOptions.Compiled 
    ); 


// This is the replacement string 
public static string regexReplace = 
     "<span class=\"$1\" lang=\"$2\" onDblClick=\"window.external."+ 
     "MyFunction(ThisLanguage)\">\r\n"; 


//// Replace the matched text in the InputText using the replacement pattern 
// string result = regex.Replace(InputText,regexReplace); 

//// Split the InputText wherever the regex matches 
// string[] results = regex.Split(InputText); 

//// Capture the first Match, if any, in the InputText 
// Match m = regex.Match(InputText); 

//// Capture all Matches in the InputText 
// MatchCollection ms = regex.Matches(InputText); 

//// Test to see if there is a match in the InputText 
// bool IsMatch = regex.IsMatch(InputText); 

//// Get the names of all the named and numbered capture groups 
// string[] GroupNames = regex.GetGroupNames(); 

//// Get the numbers of all the named and numbered capture groups 
// int[] GroupNumbers = regex.GetGroupNumbers(); 
+0

'span'과'class' 사이에있는 것을 포착 할 필요가 없습니까? * 뭔가 * 있다면? :). 이 예제에서는 단지 공간처럼 보입니다. –

+0

감사합니다 !!! 감사!!! :) – Lai

+0

@Vivin, 공정한 의견 (+1)이긴하지만 상당히 까다로운 요구라고 생각합니다. 따라서 검색 정규 표현식을 "" 대체 문자열을 ""해야합니다. – Lazarus

0

HTML을 정규식으로 구문 분석하는 것은 10 번째 지옥과 같습니다. 나는 너를 괴롭힌다. tidy (.NET이 깔끔한 지 확실하지 않음)을 실행 한 다음 XML 파서를 통해 실행하는 것이 좋습니다. 그런 식으로 classlang과 같은 특정 속성을 추출한 다음 노드에 onDblClick이라는 새 속성을 추가 할 수 있습니다. 그렇지 않으면

, 순진한 접근 방식 (확실하지 어떤 구문은 .NET에 있지만이 펄에) :

$str =~ s/<span\(.*?\)lang=\\"\(.*?\)\\">/<span$1lang=\\"$2\\" onDblClick=\\"window.external.MyFunction($2)\\">/ 

여기서 중요한 것은 패턴이 일치하는 것입니다 (캡처 포함) :

<span\(.*\)lang=\\"\(.*?\)\\"> 

이이 \"의 사이에 아무것도 lang=\" 다음, 아무것도에 의해 <span 다음과 일치, \"> 하였다.

교체 패턴은 다음과 같습니다

<span$1lang=\\"$2\\" onDblClick=\\"window.external.MyFunction($2)\\"> 

이 생성 <spanonDblClick 물건 다음 그것을 캡처 언어 이름 ($2) 다음 다음 lang ($1)와 lang=\"까지 일치하는 모든 것을, 다음 .

저는 .NET에 익숙하지 않으므로 이것을 변환해야합니다. 하지만 너무 다르지 않아야합니다. \(( (구문에 따라 다름)으로 변경해야 할 수도 있습니다. 또한 .NET에서 역 참조를 처리하는 방법을 잘 모르지만 $1$2 (예 : Java와 유사)이어야합니다.

참고 : 테스트하지 않았습니다!

1

HTML은 은 정규이 아니며 가장 간단한 시나리오를 제외한 모든 문제를 해결하기에 충분하기 때문에 일반적으로 정규 표현식을 사용하여 HTML을 구문 분석하는 것은 좋지 않습니다. 많은 시간을 Expresso 저장

+0

HTML 구문 분석 작업에 대해 정규식을 권장하지 않는 것이 밀가루를 치는 것과 같습니다. 당신이 좋아하는 모든 것을 이길 수 있습니다. 결코 먼지를 쌓지 않을 것입니다. – Tomalak

0

정규식을 사용하지 않을 것입니다. 나는 jQuery를 사용할 것이다.

// set the lang value to ThisLanguage 
$('span.Translation').attr('lang', 'ThisLanguage'); 
// add the onDblClick event with the value 
$('span.Translation').attr('onDblClick', 'window.external.MyFunction(ThisLanguage)'); 

아니면 단순히 문자열을 (당신이하지 않을 수 있지만, 경우이 작업 할 수 있습니다 어떤)를 생성하고이를 밀어 경우 왜 이러지?

string spanTag = String.Format("<span class=\"Translation\" lang=\"{0}\" onDblClick=\"window.external.MyFunction({0})\">", "ThisLanguage"); 
+0

C# 용 jQuery 포트가 있습니까? 좋은! ;-) – Tomalak