0

Is there any way where I can display all characters and strings except a certain set of words or range of numbers, using Java? For example:

Regex:

^(if|else),[0-9] 

Input String:

if x <= 7

Output:

Unrecognized Tokens:

x , <=

Since "if" and 7 are negated, they won't appear. Can I negate set of strings and range of numbers all in a single regular expression? Or is there any other way that I can just display the unmatched strings? Our assignment is to display the recognized tokens, then the unmatched tokens. I've researched and studied regex for three days, but I still can't get my assignment done. Thanks in advance for any help.

4

3 に答える 3

1

問題の複雑さに応じて、否定的な先読みアサーションを試すことができます。

\b((?!if|else|\d)\w+)\b

または、後読みと否定先読みのクレイジーな組み合わせ:

((?<=\A|\s)(?!if|else|\d)\S+)
于 2011-08-30T17:46:01.403 に答える
1

String.split()を使用して文字列をトークンに分割し、各トークンを「フィルター リスト」と比較します。

正規表現を使用してこれを達成できたとしても、それほど簡単ではありません。

編集:

実際、結果を繰り返し処理する必要さえないかもしれません。「フィルター」という言葉で分割される可能性があります。例えば:

String[] results = s.split(" *if *| *else *| *[0-9]+ *| +");

x <=結果で単一のトークンになりたくないので、式に空白を入れる必要があることに注意してください。また、キーワードの前後に空白を追加すると、結果セットに空の文字列が含まれないようになります。

于 2011-08-30T17:28:26.813 に答える
0

うん、語彙素 (if、else、main) をトークン (キーワード) として 0-9 を NUM として分類する必要があります...

\b((?!if|else|\d)\w+)\ おっと、残念ながら動作します。誤って削除してしまいました | .

于 2011-08-30T18:03:25.440 に答える