1

I’m trying to create a regex that matches strings that have /x+any number/ in them, where anything can be written before or after that.

I tried creating the following regex .*/x+\\d*/.*

An example of a string I’m trying to match is abc/x+10/tomorrow

Strings such as abc/x+/tomorrow should evaluate to false but is true.

5
  • is that + literal? Or are you saying you want any number of xs as long as there is one. Also, are you sure that an input whit out any number is valid? Commented Sep 18, 2019 at 0:46
  • 1
    Hi! Nice question :-) You could improve it, if you provide some sample strings and a little source code. Commented Sep 18, 2019 at 0:48
  • Your regex seems to work fine, did you escaped all the literals properly ? Regex Demo .*\/x\+\d*\/.* Commented Sep 18, 2019 at 1:00
  • It works now with the escape characters but found a different error, that I mention in the edited post Commented Sep 18, 2019 at 1:11
  • 1
    @Carl you need to change \d* to \d+ to make sure atleast one digit should be there Commented Sep 18, 2019 at 1:15

3 Answers 3

3

You were very close, all you needed to do was escape all the / and +, and change \d* (match between 0 and unlimited) to \d+ (match between 1 and unlimited) in order to avoid matching abc/x+/tomorrow:

.*\/x\+\d+\/.*

Regex Demo

Sign up to request clarification or add additional context in comments.

Comments

1

You could use for example findFirstIn which will return an Option.

You should match 1+ digits instead and the patten can be shortened to /x\+\d+/

val pattern = """/x\+\d+/""".r
pattern.findFirstIn("abc/x+10/tomorrow").isDefined
pattern.findFirstIn("abc/x+/tomorrow").isDefined

Output

res0: Boolean = true
res1: Boolean = false

Scala demo

Comments

0

Maybe,

^.*?x\+\d+.*$

might simply work with proper language-based escapings.

Demo


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


2 Comments

It should evaluate to false.
abc/x+10tomorrow should evaluate to false but is not but your regex is matching this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.