スキップしてメイン コンテンツに移動

投稿

ラベル(Regex)が付いた投稿を表示しています

Regex: Detect Repeated String Chunks

Target strings I am trying to detect string which contains repeated string pattern like below. .....ABCDABCDABCD..... "ABCD" is just an example, it can be any fixed length of string chunk. Solution Regex Thinking for a bit and finally reached the solution regex which meets my demand is something like below. (.{4,})\\1{3,} The above regex matches string whose length of the chunk is more than 4 and it should be repeated equal or more than 4 times. In more general regex is below (using pattern formatting). String.format("(.{%d,})\\1{%d,}", minChunkLen, times-1) Java Code Ok you know I am Java lover, I will show you full regex code with test cases. If you found any bugs on the code please feel free to comment. public static final boolean isRepeatedStrIn(String input, int minChunkLen, int times) { return input.matches(String.format("(.{%d,})\\1{%d,}", minChunkLen, times-1)); } package com.dukesoftware.utils.common; import java.util.Array

C#: Extract Charset from Html Meta Tag

private static readonly Regex META_TAG_CHARSET_REGEX = new Regex(@"<META\s+http-equiv\s*=\s*Content-Type\s+content=\s*""[^""]*\s+charset\s*=\s*(?<charset>[^""\s]*).*""\s*>", RegexOptions.IgnoreCase | RegexOptions.Compiled); public static string ExtractCharset(string htmlText) { string result = null; var m = META_TAG_CHARSET_REGEX.Match(htmlText); if (m.Success) { result = m.Groups["charset"].Value; } return result; } Note: System.Text.RegularExpressions.Regex class is thread safe according to this msdn doc .

「特定の文字から始まらない文字列」にマッチする正規表現

「特定の文字から始まらない文字列」 にマッチする正規表現の例です。  以下の例では、Aから始まらない文字列にマッチする正規表現を示しています。 ^(?!A).*$ 私も正規表現の組み方で四苦八苦することがあります。以下の書籍は実践的に様々な正規表現のパターンを例示してくれているので、重宝しています。

特定の文字列のみを取り除く正規表現

特定の文字列のみを取り除く正規表現は、以下のように表現します。 ^(?:(?!ABCD|XYZ)).)[A-Z]+ 上記のパターンは、ABCDとXYZのみを除く、任意のAからZの一文字以上の組み合わせにマッチします。 マッチしない文字列を新たに追加する場合、例えばIJKをマッチさせたくない場合は、 ^(?:(?!ABCD|XYZ|IJK)).)[A-Z]+ のようにすればOKです。