匹配“ - ”有完全出乎意料的结果

时间:2015-12-30 06:20:06

标签: java regex

我的表达式可以是#ifdef __CYGWIN__ #undef __STRICT_ANSI__ #endif 13.3315.66-17.22。我希望能够弄清楚它是否有17.33-17.66(en-dash),因为这将改变我的代码运行方式。我跟着this线程检查表达式中的匹配项。

我找到en-dash的正则表达式为"-"。我的正则表达式在线工作,可以看作here,但在Java中使用时失败。我的代码如下。

"-"

使用条目Pattern p = Pattern.compile("-"); Matcher m = p.matcher(refVal); System.out.println(m.find()); if (m.find()){ //Do stuff } ,代码会打印17.33–17.66 ref

预期用例:

false

2 个答案:

答案 0 :(得分:6)

问题是在输入字符串中,短划线为-(150 ascii),而模式中的短划线为<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/myCardView" android:layout_width="match_parent" android:layout_height="match_parent" card_view:cardBackgroundColor="@android:color/transparent" card_view:cardElevation="0dp"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_edit" android:background="@android:color/transparent"/> </android.support.v7.widget.CardView> (45 ascii)。 Reference

答案 1 :(得分:3)

如果你想检查em-dash(或任何单个字符)的存在,你可以使用String.contains,你不需要使用正则表达式。

refVal.contains("—")

要确保您正在测试em-dash,可以使用它的Unicode代码进行检查:

refVal.contains("\u2014")