简体   繁体   中英

Match any string regex

I am attempting to match any string of charicters using regular expressions in Java but have encounted a problem. I am trying to replace where a string contains %key% with the corrasponding value from a hashmap.

My currant regex pattern is %([.]+)% which seems to not work but I'm not sure why. I have tried %([az AZ 0-9])% which seems to work fine but I would like to allow all charichters but new line and "." does not seem to allow anything but fullstops(eg %...% will worb but %test% won't.

I'm honestly not sure what I have done wrong, I assume I am using the fullstop in the wrong place but can't seem to find how to use it correctly.

Sorry for the horrible explaination, I can't think of how to put it better.

Thanks.

I would like to allow all charichters but new line and "."

You can use this negation based regex:

%([^.%\\n\\r]*)%

[^.%\\\\n\\\\r] means match anything but DOT OR % OR new line characters

Use (?<=%)(.+?)(?=%) .

EXPLANATION

说明

Sample code:

HashMap<String , String> map=new HashMap<>();
map.put("1", "one");
map.put("2", "two");
map.put("3", "three");
String line="%123%";

Pattern pattern=Pattern.compile("(?<=%)(.+?)(?=%)");
Matcher matcher=pattern.matcher(line);
if(matcher.find()){
      String match=matcher.group();
      Iterator<String> it=map.keySet().iterator();
       while(it.hasNext()){
           String key=it.next();
           if(match.contains(key)){
                line=line.replace(key, map.get(key).toString());
           }

        }
            System.out.println(line);
 }

OUTPUT

%onetwothree%

Try:

System.out.println("%sdfsdf%".matches("^%.+%$"));

I think in some situations Regex only is not enough - you should do some logic also. You can try with StringBuilder .

You want to use something like:

%([^.]+?)%

The ? means non-greedy. The [^.] means not full stop.

Given the input:

%inside1%something%inside2%

It will match %inside1% and %inside2%

The problem with [.] is that it is literally a full stop.

Edit If you are matching line by line, then mine will be fine. If you are matching across multiple lines then you should use anubhava answer which will explicitly exclude linebreaks from the match, so multiline queries that match % across lines will be excluded from the results.

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