正则表达式与特定字符匹配或匹配为空

时间:2017-02-02 07:33:42

标签: regex mongodb

我的字符串列表是,

1. bc     // should match
2. abc    // should not match
3. bc-bc  // should match
4. ab-bc  // should match
5. bc-ab  // should match

我希望匹配所有bc。如果它以字符串1中的任何其他字符开头,例如a,我不想匹配。

我尝试使用正则表达式[^a]bc。它不匹配字符串2以及字符串1和5,因为[]需要一个字符。然后我尝试了[^a]?bc。它也匹配字符串2。如何使正则表达式匹配空或不匹配特定的字符列表?

1 个答案:

答案 0 :(得分:1)

您是否希望仅在bc前面没有特定字符集(例如axy时才匹配(?<![axy])bc )?那就是negative lookbehind assertion的确切含义:

bc

将匹配bbcabc,但不会匹配ybcbc

如果您想将\bbc\b 作为一个完整的&#34;字符#34;,i。即不与任何字母或数字相邻,请使用word boundary anchors

{ name: { $regex: '(?<![axy])bc' } }

请注意,在MongoDB中,为了能够使用仅适用于PCRE引擎(而不是JavaScript)的lookbehind等功能,您需要遵循某种语法(使用字符串而不是正则表达式对象),例如:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.sharannya.androidspeakerrec"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
        ndk {
            abiFilters "armeabi-v7a","armeabi"
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.0'
    testCompile 'junit:junit:4.12'
}
相关问题