RSS

タグ別アーカイブ: 正規表現

C#: 正規表現

C# で正規表現を使うには、System.Text.RegularExpressions 名前空間をインポートする必要がある。

その名前空間に含まれる Regex クラスのメソッドを利用することにより、様々な正規表現処理が可能である。

// 正規表現
using System.Text.RegularExpressions;

Action<Object> println = o => Console.WriteLine(o.ToString());
Func<String> getPwd = () => Environment.CurrentDirectory;

println("<< 正規表現 >>");
var pwd = getPwd();  // カレントディレクトリを得る。
println(pwd);

// カレントディレクトリが Windows 風か調べる。
var b = Regex.IsMatch(pwd, @"\w:\\w*");
println(b);

// パターンに一致したワードを列挙する。(ドライブ名とサブディレクトリ名)
MatchCollection mc = Regex.Matches(pwd, @"\w+");
foreach (Match m in mc)
{
  println(m.Value);
}

 
コメントする

投稿者: : 2024/04/28 投稿先 C#, dotNET

 

タグ:

Crystal: 正規表現

Crystal では Regex クラスのメソッドを使って正規表現処理を行うことができる。

このクラスでは、=~ や $~ のような Perl 風の演算子や特殊変数も使用できる。

下に Regex クラスの簡単な使用例を示す。

# 正規表現 Regex https://crystal-lang.org/api/1.9.2/Regex.html

str = "無職転生S2"
p /転生/ =~ str  # 見つかった位置を表示 (バイト位置でなく文字列の位置)
if match_data = /S\d/.match(str)
  p match_data.string  # 検索した文字列
  p match_data[0]  # 見つかった文字列
  p! $~  # Perl 風の特殊変数も使える。
end

/\d/.match_at_byte_index("F15J F35B", 3)  # 数字を 3 バイト目から検索する。
p! $~[0]  # 見つかったバイト位置

このコードの実行例を下に示す。

$ ./bin/regex
2
"無職転生S2"
"S2"
$~ # => Regex::MatchData("S2")
$~[0] # => "3"
$
 
コメントする

投稿者: : 2023/09/20 投稿先 Crystal

 

タグ: ,

Nim の正規表現

Nim で正規表現を利用するには re モジュールをインポートする必要がある。

このモジュールには正規表現に関する様々な proc が含まれている。

以下にそのサンプルを示す。

# 正規表現 https://nim-lang.org/docs/re.html
import re

const S1 = "Abcdefghijkl."
const S2 = "9,7:8,4"

# match
echo match(S1, re(".*def.*"), 0)  # 先頭から  = true
echo match(S1, re(".*def.*"), 5)  # 5文字目から = false

# startsWith, endsWith
echo startsWith(S1, re(r"Ab")) # = true
echo endsWith(S1, re(r"\."))   # = true

# contains
echo contains(S1, re(r"ghi"))  # = true
echo contains(S1, re(r"GHi"))  # = false

# split
let seq1 = split(S2, re"[,|:]")
echo seq1  # = @["9", "7", "8", "4"]

# replace
let seq2 = replace(S2, re"[,|:]", "_")
echo seq2  # = 9_7_8_4

このサンプルの実行例を下に示す。

> ./bin/regex
true
false
true
true
true
false
@["9", "7", "8", "4"]
9_7_8_4
 
コメントする

投稿者: : 2023/09/13 投稿先 Nim

 

タグ: ,

PowerShell の勉強:正規表現

-match , -cmatch 演算子

これらの演算子は「一致」を判断します。-match は大文字と小文字を区別せずに一致を判別します。一方、-cmatch は大文字と小文字を区別します。

「比較対象の文字列 -match 正規表現」のように使用しますが、正規表現の部分は単純な文字列だったりワイルドカードも使用できます。

(例)

$a = "get-childitem"
# -match は大文字・小文字を区別しない。
$a -match "get-"  # True
$a -match "GET-"  # True
# -cmatch は大文字・小文字を区別する。
$a -cmatch "get-"  # True
$a -cmatch "GET-"  # False
# ワイルドカードを使う
$a -match "GET-*"  # True
# 正規表現を使う
$a -match "[0-9]+"  # False
$a -match "[a-z]+"  # True

-replace, -creplace 演算子

-replace 演算子は対象文字列内の正規表現で一致した部分文字列を他の文字列で置き換えます。

「対象の文字列 -replace 正規表現, 置換する文字列」のように使用しますが、「正規表現」の部分は単純な文字列やワイルドカードでも構いません。

-replace は大文字と小文字を区別しませんが、-creplace は区別します。

(例)

$a = "set-location c:\temp"
$a
$b = $a -replace "set", "push"
$b
$b = $a -creplace "set", "push"  # 大文字・小文字を区別するので結果的に何もしない。
$b
$b = $a -replace "\sc:\\", " /home/user/"
$b

実行例

set-location c:\temp
push-location c:\temp
push-location c:\temp
set-location /home/user/temp
 
コメントする

投稿者: : 2022/07/16 投稿先 PowerShell

 

タグ: ,

PowerShell の勉強:grep みたいなことをする

Select-String コマンドレット

Select-String コマンドレットは、テキストファイル内を検索して指定した文字列が含まれているか調べます。

デフォルトでは、見つかったパスとその行番号とその行自身を表示します。

(使用例)

select-string -path c:\bin\nppp.ps1 -pattern "start"

C:\bin\nppp.ps1:2:  start-process "C:\Program Files\Notepad++\notepad++.exe" $args[0]
C:\bin\nppp.ps1:6:  start-process "C:\Program Files\Notepad++\notepad++.exe"

Select-String コマンドレットではパスの指定にワイルドカードが使えるので、grep コマンドのようなこともできます。

(使用例)

select-string -path c:\bin\*.ps1 -pattern "C:\"

-pattern オプションには正規表現が使えます。

(使用例)

select-string -path c:\bin\*.ps1 -pattern ".+\-location.*"

さらに、-pattern オプションにはワイルドカードも使えます。

(使用例)

select-string -path c:\bin\*.ps1 -pattern "loc*"

(注意事項) 一般に PowerShell の正規表現では大文字と小文字の区別がありません。区別が必要な場合は、-CaseSensitive オプションを指定します。

Select-String コマンドレットが返す各行の型

Select-String コマンドレットが返す各行の型は Microsoft.PowerShell.Commands.MatchInfo です。

下にこの型のプロパティとメソッドを示します。

Properties

ContextThe context for the match, or null if -context was not specified.
FilenameReturns the base name of the file containing the matching line. It will be the string “InputStream” if the object came from the input stream. This is a readonly propery calculated from Path.
IgnoreCaseIndicates if the match was done ignoring case.
LineReturns the text of the matching line.
LineNumberReturns the number of the matching line.
MatchesA list of all Regex matches on the matching line.
PathThe full path of the file containing the matching line. It will be “InputStream” if the object came from the input stream.
PatternReturns the pattern that was used in the match.

Methods

RelativePath(String)Returns the path of the matching file truncated relative to the directory parameter. For example, if the matching path was c:\foo\bar\baz.c and the directory argument was c:\foo the routine would return bar\baz.c
ToEmphasizedString(String)
ToString()Returns the string representation of this object. The format depends on whether a path has been set for this object or not. If the path component is set, as would be the case when matching in a file, ToString() would return the path, line number and line text. If path is not set, then just the line text is presented.
ToString(String)Returns the string representation of the match object same format as ToString() but trims the path to be relative to the directory argument.
 
コメントする

投稿者: : 2022/07/16 投稿先 PowerShell

 

タグ: , , ,