I need to get the numbers only in between either the dash or underscore or if the number is not between, get the last part after the underscore or dash. Right now I only managed to get the numbers only. Pls only adjust on the "Display Name" TextField. The given should be put on the "Name" TextField.
For example:
Example 1: AB2C_192_A9
Expected Output: 192
Example 2: AB2C-192_A9
Expected Output: 192
Example 3: AB2C-192-A9
Expected Output: 192
Example 4: AB2C-192
Expected Output: 192
Example 5: 192
Expected Output: 192
Example 6: ABC_192Z
Expected Output: 192
Code
<TextField
disabled
label="Display Name"
variant="outlined"
value={value && value?.match(/\d /g)?.join("")}
/>
[](https://codesandbox.io/s/basictextfields-material-demo-forked-v22563?
CodePudding user response:
You can use
<TextField
disabled
label="Display Name"
variant="outlined"
value={(value.match(/(?:^|[-_])(\d )(?=[_-]|[^\d_-]*$)/) || ['',''])[1]}
/>
Here,
(?:^|[-_])
- matches either start of string, or-
, or_
(\d )
- Capturing group 1: one or more digits(?=[_-]|[^\d_-]*$)
- either a-
or_
or any zero or more chars other than digits,_
and-
chars till the end of string.
See the regex demo.