Javaでスキャナーを使用して、弦が正規表現パターンではない場合、どうすればastring(astring)できますか?

StackOverflow https://stackoverflow.com/questions/1506249

  •  19-09-2019
  •  | 
  •  

質問

私は自分の質問が述べているようにやろうとしていますが、一致を見つける次のコードがあります。

String test = scan.next();
if (test.equals("$let"))
return 1;

ただし、トークンを消費しないようにHasNextを使用することをお勧めします。ただし、次のことを行うと失敗します。
if (scan.hasNext("$let"))
return 1;

私は、与えるとき、次にパターンを期待する変数があることを理解していますが、私はそれが機能するはずのregexシンボルを持っていないと思いました。また、$はおそらくいくつかの正規表現シンボルだと思ったので、 /$を試しましたが、うまくいきませんでした!

助けてくれてありがとう!

役に立ちましたか?

解決

You should use \\$ to escape the regex, but it's easier to just get the next() and save the result.

他のヒント

In general, if you have some arbitrary string that you want to match literally with no meanings to any regex metacharacters, you can use java.util.Pattern.quote.

Scanner sc = new Scanner("$)}**");
System.out.println(sc.hasNext(Pattern.quote("$)}**"))); // prints "true"
System.out.println(sc.hasNext("\\Q$)}**\\E")); // prints "true"
System.out.println(sc.hasNext("$)}**")); // throws PatternSyntaxException

You can also use the \Q and \E quotation markers, but of course you need to ensure that the quoted string must not itself contain \E.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top