简体   繁体   中英

Regular expression not matching on first and last word of string

I am trying to write a java program that will look for a specific words in a string. I have it working for the most part but it doesnt seem to match if the word to match is the first or last word in the string. Here is an example:

"trying to find the first word".matches(".*[^a-z]find[^a-z].*") //returns true
"trying to find the first word".matches(".*[^a-z]trying[^a-z].*") //returns false
"trying to find the first word".matches(".*[^a-z]word[^a-z].*") //returns false

Any idea how to make this match on any word in the string?

Thanks in advance,

Craig

The problem is your character class before and after the words [^az] - I think that what you actually want is a word boundary character \\b (as per ColinD's comment) as opposed to not a character in the az range. As pointed out in the comments (thanks) you'll also needs to handle the start and end of string cases.

So try, eg:

"(?:^|.*\b)trying(?:\b.*|$)" 

您可以使用可选(?),检查以下链接并测试更多案例,如果这样可以提供正确的输出: https//regex101.com/r/oP5zB8/1

 (.*[^a-z]?trying[^a-z]?.*)

I think (^|^.*[^az])trying([^az].*$|$) just fits your need.

Or (?:^|^.*[^az])trying(?:[^az].*$|$) for non capturing parentheses.

You can try following program to check the existence on start and end of any string:

package com.ajsodhi.utilities;

import java.util.regex.Pattern;

public class RegExStartEndWordCheck {

    public static final String stringToMatch = "StartingsomeWordsEndWord";

    public static void main(String[] args) {

        String regEx = "Starting[A-Za-z0-9]{0,}EndWord";
        Pattern patternOriginalSign = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
        boolean OriginalStringMatchesPattern = patternOriginalSign.matcher(stringToMatch).matches();
        System.out.println(OriginalStringMatchesPattern);
    }
}

you should use the boundary \\b that's specify a beginning or a ending of a word instead of [^az] which is not so logic. Just something like

".*\\bfind\\b.*" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM