Reputation: 4049
Text is: "R1 AND R24 OR R456'
I want to write a pattern that can find R and the numbers (only numbers) following it. So the matches will be: R1, R24, R456.
How can I write appropriate regex?
Upvotes: 0
Views: 201
Reputation: 4339
The topic of your question says "Replace" but I can't find any points concerning possible replacement in your question.
The regex pattern /R[0-9]+/
should work to find "R1", "R24", and "R456" in "R1 AND R24 OR R456".
To extract the numbers following the respective "R" you can add a group to the regex pattern: /R([0-9]+)/
. Then you can just "match" the test string against the regex pattern and extract group 1 for each match:
Target String: R1 AND R24 OR R456
Regex Pattern: R([0-9]+)
"find next"; group(0): R1; group(1): 1
"find next"; group(0): R24; group(1): 24
"find next"; group(0): R456; group(1): 456
"find next"; null
Which programming language are you using? We could then provide an even concreter example.
Upvotes: 0
Reputation: 1381
\d+ represents "one or more" of whatever \d represents
As other people pointed out, you can use \b to represent a "beginning of word" if you want to avoid matching the end of words like "thumb2"
The exact syntax of how to apply a regex varies from language to language: in Perl, you type something very like the /.../ syntax above. In other languages, you may use a string "R\d+" passed to a function. In some you need the slashes inside a string.
You can test it online, eg: http://www.fileformat.info/tool/regex.htm
Upvotes: 1
Reputation: 93046
Something like
\bR\d+
See it here on Regexr
\b
is a anchor for a word boundary, that means here there can be no word character (letter, number and _) before the R
\d
is a digit
+
one or more
If you want to replace the numbers you can do so (if your language supports lookbehinds)
(?<=\bR)\d+
See here on Regexr
For the correct syntax you need to tell us your language.
Upvotes: 2
Reputation: 33928
The regex would be \bR\d+
. To also capture the number you can use \bR(\d+)
.
Upvotes: 1