hey i wonder to group all the numbers include the slashes
i have strings like this
- some text 156/6
- other text 54/966
- another text 1/9
and so on ..
i want to group this from the results i mean the numbers include the slashes
like this 156/6 54/966 1/9
i tried this but its not working if i add and letter txt before or after the numbers with slashes
^\d (\/\d )*$
CodePudding user response:
Since you're specifying ^
and $
you're requiring the entire string to be the numbers with slashes, which is why it doesn't pick up the group if you put text before.
Also, if you want to capture the entire number slash number string and not just the second half of the slash, you should put the entire regex inside a capture group.
This should work: (\d \/\d )
Example: https://regexr.com/6lfii
CodePudding user response:
(\d{1,}[\/]{1}\d{1,})
You can test it here. I hope that was helpful.
CodePudding user response:
It isn't clear to me if you have several targets per string or just one...
The regexp you have here can't work because it will only match strings that have exactly the target format. ^
only matches at the start of the string, and $
at the end. So
/^\d (\/\d )*$/.test("123/456")
is true/^\d (\/\d )*$/.test("x123/456")
is false/^\d (\/\d )*$/.test("123/456x")
is also false
Also, you are using a capturing group (\/\d )
where a non-capturing one would suffice and would be more efficient (less work, fewer memory allocations).
If you have one target per string, then str.match(/\d (?:\/\d )*/)
would work.
If you need to extract several, you can use str.match(/\d (?:\/\d )*/g)
.
const test1 = "hello 123/456"
const test2 = `hello 12/34
sup 56/78/90`
console.log(test1.match(/\d (?:\/\d )*/))
console.log(test2.match(/\d (?:\/\d )*/g))
CodePudding user response:
Regex tester
Use on-line tester to verifying and fill in the following strings in the fields.
Regex type switch is set to Javascript.
Field Regular expression to test
[a-zA-Z ] (\d )(\/\d )\n*
Field String to test
some text 156/6
other text 54/966
another text 1/9
Field Substitution
Attention, there must be one space at the end!
$1$2
The result can be seen under substitution:
156/6 54/966 1/9