Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression - followed by

How can I write a regex that match this

123/456

123/456/?

but not this

123/456/

I want on the second / it must be followed by a ?.

For Example I would like it to match this

'123/456'.match(X) // return ['123/456']
'123/456/?'.match(X) // return ['123/456/?']
'123/456/'.match(X) // return null

Update

I missed to say one important thing. It must not end with '?', a string like '123/456/?hi' should also match

like image 960
Codler Avatar asked Apr 24 '12 06:04

Codler


People also ask

What are the rules for regular expression?

The set of regular expressions is defined by the following rules. Every letter of ∑ can be made into a regular expression, null string, ∈ itself is a regular expression. If r1 and r2 are regular expressions, then (r1), r1. r2, r1+r2, r1*, r1+ are also regular expressions.

What does *$ mean in regex?

*$ means - match, from beginning to end, any character that appears zero or more times. Basically, that means - match everything from start to end of the string.

How do you chain in regex?

Chaining regular expressions Regular expressions can be chained together using the pipe character (|). This allows for multiple search options to be acceptable in a single regex string.

What will the '$' regular expression match?

By default, regular expressions will match any part of a string. It's often useful to anchor the regular expression so that it matches from the start or end of the string: ^ matches the start of string. $ matches the end of the string.


3 Answers

You can try this regex: \d{3}/\d{3}(/\?.*)?

It will match

  • 3 digits
  • followed by a /
  • followed by 3 digits
  • followed by /?any_text (e.g. /?hi) (optional)

This example uses regular expression anchors like ^ and $, but they are not required if you only try to match against the target string.

var result = '123/456/?hi'.match(/\d{3}\/\d{3}(\/\?.*)?/);
if (result) {
    document.write(result[0]);
}
else {
    document.write('no match');
}
like image 151
splash Avatar answered Sep 21 '22 00:09

splash


This regular expression will work /^\d{3}\/\d{3}(\/\?.*)?/

See this JSFiddle.

Note: if you think it should match any number of digits then use \d+ instead of \d{3}. The later matches exactly 3 digits.

like image 39
Shiplu Mokaddim Avatar answered Sep 19 '22 00:09

Shiplu Mokaddim


Here you are:

[0-9]+/[0-9]+(/\?[^ ]*)?
like image 27
sp00m Avatar answered Sep 19 '22 00:09

sp00m