Regular Expression - Starting with and ending with string

java regex string

238 观看

3回复

3 作者的声誉

I would like to write a regular expression to match files that starts with "AMDF" or "SB700" and does not end with ".tmp". This will be used in Java.

作者: martinezjosei 的来源 发布者: 2017 年 12 月 27 日

回应 3


0

42375 作者的声誉

An approach could be to try a regex using a negative lookahead to assert that the file name does not end on .tmp and use an anchor ^ to make sure that the file name starts with AMDF or SB700 like:

^(?!.*\.tmp$)(?:AMDF|SB700)\w*\.\w+$

Explanation

  • The beginning of the string ^
  • A negative lookahead (?!
  • To assert that the string ends with .tmp .*\.tmp$
  • A non capturing group which matches AMDF or SB700 (?:AMDF|SB700)
  • Match a word character zero or more times \w*
  • Match a dot \.
  • Match a word character one or more times \w+
  • The end of the string $

In Java it would look like:

^(?!.*\\.tmp$)(?:AMDF|SB700)\\w*\\.\\w+$

Demo

作者: The fourth bird 发布者: 2017 年 12 月 27 日

0

14596 作者的声誉

决定

Code

See regex in use here

^(?:AMDF|SB700).*\.(?!tmp$)[^.]+$

Usage

See code in use here

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        final String regex = "^(?:AMDF|SB700).*\\.(?!tmp$)[^.]+$";
        final String[] files = {
            "AMDF123978sudjfadfs.ext",
            "SB700afddasjfkadsfs.ext",
            "AMDE41312312089fsas.ext",
            "SB701fs98dfjasdjfsd.ext",
            "AMDF123120381203113.tmp"
        };

        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);

        for (String file:files) {
            final Matcher matcher = pattern.matcher(file);
            if(matcher.matches()) {
                System.out.println(matcher.group(0));
            }
        }
    }
}

Results

Input

AMDF123978sudjfadfs.ext
SB700afddasjfkadsfs.ext

AMDE41312312089fsas.ext
SB701fs98dfjasdjfsd.ext
AMDF123120381203113.tmp

Output

Below shows only matches.

AMDF123978sudjfadfs.ext
SB700afddasjfkadsfs.ext

Explanation

  • ^ Assert position at the start of the line
  • (?:AMDF|SB700) Match either AMDF or SB700 literally
  • .* Match any character any number of times
  • \. Match a literal dot . character
  • (?!tmp$) Negative lookahead ensuring what follows doesn't match tmp literally (asserting the end of the line afterwards so as not to match .tmpx where x can be anything)
  • [^.]+ Match any character except . one or more times
  • $ Assert position at the end of the line
作者: ctwheels 发布者: 2017 年 12 月 27 日

0

1 作者的声誉

Here is another example that works:

^(SB700|AMDF).*(?!\.tmp).{4}$

作者: Nick Villa 发布者: 2017 年 12 月 27 日
32x32