dポイントプレゼントキャンペーン実施中!

Bシェルの正規表現を教えてください。
ある文字列の中に英数大文字、小文字、コンマ、ピリオド、アンダーバー、ハイフン以外が含まれていないかをチェックしたいです。以下のようにすると文字列LINEの先頭にあるとチェックできるのに、中にあると出来ません。教えてください。
if expr \"$LINE\" : [^a-zA-Z0-9\\,\\.\\_\\-] >/dev/null ; then
echo \"チェックNG 使用不可能な文字が入っています。 ${LINE}\" >> ${LOG_FILE}
else
echo \"チェックOK ${LINE}\" >> ${LOG_FILE}
fi

A 回答 (4件)

「以外」を調べるよりも、文字列が指定の文字だけで始めから終りまで構成されている事を確認する方が簡単かと思われます。



if expr "$LINE" : "^[A-z0-9,._-]*$" > /dev/null; then
echo "OK"
...

でどうでしょうか。

この回答への補足

「^」を削除したらエラーがなくなりました。また期待通りに動きました。ありがとうございました。

補足日時:2009/03/23 15:49
    • good
    • 0
この回答へのお礼

ご回答ありがとうございます。
「^」を前に出してやってみたのですが、以下のようなエラーが表示されてしまいます。実行結果は期待通りっぽいのですが、このエラーは無視してもよいのでしょうか?ご教授お願いいたします。

expr: 警告: 可搬でない BRE: `^[a-zA-Z0-9\,\.\_\-]*$': 基本的な正規表現の最初の文字として
`^' を使うことは可搬ではないので無視します

お礼日時:2009/03/23 15:31

お使いのシステムは具体的になんでしょうか?



http://opengroup.org/onlinepubs/007908775/xbd/re …
にある仕様から考えても、

Regular Expressions
" BRE Expression Anchoring
A BRE can be limited to matching strings that begin or end a line; this is called anchoring. The circumflex and dollar sign special characters will be considered BRE anchors in the following contexts:

1. A circumflex (^) is an anchor when used as the first character of an entire BRE. The implementation may treat circumflex as an anchor when used as the first character of a subexpression. The circumflex will anchor the expression (or optionally subexpression) to the beginning of a string; only sequences starting at the first character of a string will be matched by the BRE. For example, the BRE ^ab matches ab in the string abcdef, but fails to match in the string cdefab. The BRE \(^ab\) may match the former string. A portable BRE must escape a leading circumflex in a subexpression to match a literal circumflex.

3. A BRE anchored by both "^" and "$" matches only an entire string. For example, the BRE ^abcdef$ matches strings consisting only of abcdef. "

先頭に ^ を置くことが可搬性を損なうとは思えないのですが。
警告のメッセージを使って検索してみると、

http://japo.sourceforge.jp/trans/ja/sh-utils-2.0 …
などで

#: src/expr.c:439
#, c-format
msgid ""
"warning: unportable BRE: `%s': using `^' as the first character\n"
"of the basic regular expression is not portable; it is being ignored"
msgstr ""
"警告: 可搬でない BRE: `%s': 基本的な正規表現の最初の文字として\n"
"`^' を使うことは可搬ではないので無視します"

というのが見つかりますが、GNU の expr はこれに該当しませんし。
ところで「基本的な正規表現の」というのは誤訳ですね。
basic regular expression でひとつの単語ですので、ここでは「基本的な」
と訳してはいけません。

それともうひとつ。[] の中では . は\を前置する必要はないですよ。
, や_ は元からメタ文字ではないのでこれにも不要です。
- については微妙ですが、閉じのブラケットの直前に置けば\は不必要です。
    • good
    • 0
この回答へのお礼

sakusaker7さんご回答ありがとうございます。
[]の中では前置しなくていいんですね。了解しました。
「^」の件はよく分からないのであきらめます。ありがとうございました。

お礼日時:2009/03/24 16:12

if expr "$LINE" : .*[^a-zA-Z0-9\,\.\_\-] ...


としてはいかがでしょう。
# 正規表現の先頭に ".*" を付ける。
    • good
    • 0

>^a-zA-Z0-9\\,\\.\\_\\-


\で\がエスケープされて・・・ ってオチでは?
    • good
    • 0
この回答へのお礼

「\」は投稿した際に2つになったみたいです。
実ソース上は「\」は一つです。

お礼日時:2009/03/23 13:12

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!