简体   繁体   中英

Regular expression for matching texts before and after string

I would like to match URL strings which can be specified in the following manner. xxx .yyy.com (For example, the regular expression should match all strings like 4xxx.yyy.com, xxx4.yyy.com, xxx.yyy.com, 4xxx4.yyy.com, 444xxx666.yyy.com, abcxxxdef.yyy.com etc).

I have tried to use

([a-zA-Z0-9]+$)xxx([a-zA-Z0-9]+$).yyy.com

([a-zA-Z0-9]*)xxx([a-zA-Z0-9]*).yyy.com

But they don't work. Please help me write a correct regular expression. Thanks in advance.

Note: I'm trying to do this in Java.

If you want to make sure there is xxx and you want to allow all non whitespace chars before and after. If you want to match the whole string, you could add anchors at the start and end.

Note to escape the dot to match it literally.

^\S*xxx\S*\.yyy\.com$
  • ^ Start of string
  • \S*xxx\S* Match xxx between optional non whitespace chars
  • \.yyy Match .yyy
  • \.com Match .com
  • $ End of string

Regex demo

In Java double escape the backslash

String regex = "^\\S*xxx\\S*\\.yyy\\.com$";

Or specify the characters on the left and right that you would allow to match in the character class:

^[0-9A-Za-z!@#$%^&*()_+]*xxx[0-9A-Za-z!@#$%^&*()_+]*\.yyy\.com$

Regex demo

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