简体   繁体   中英

Selecting just “th” from “11th March” using regex

How can I replace th, nd, st from the following data using regex with anything say a space.

my random text goes here with th in it..... "11th March" ....my random text goes here with th in it. my random text goes here with nd in it..... "02nd March" ....my random text goes here with nd in it. my random text goes here with st in it..... "01st March" ....my random text goes here with st in it.

So far I tried this [0-9]0-9 but it also replaces the number. How do I retain digits or just select those required parts?

(?<=\\d)(th|rd|nd|st)

正向后看

You can capture the number characters and match the following th , nd , st .

Usually a back-reference is either $1 or \\1 for the first match of a pattern in parentheses.

Try the following:

Find: ([0-9]+)[a-zA-Z]{2}
Replace: $1 

See Live demo

In php, the following code snippet works to do the find-and-replace of st , nd , etc immediately after a digit, and replacing it with ** . You can see where you can insert "any string" for replacement.

With a big tip of the hat to @jaco0646 !

<?php
$inputString = 'This is the 2nd of November<br>';
$pattern = '/(?<=[0-9])(st|nd|rd|th)/';
$replacement = '**';

$newString = preg_replace($pattern, $replacement, $inputString);
echo $inputString;
echo $newString;
?>

Consider the following Regex...

(?<=\"\d+)[a-zA-Z]+

Good Luck!

As Johnsyweb suggests, the exact syntax of the replace command will depend on what language you are using.
jaco0646 has a good regex for matching what you want, and, critically, captures it. (The second set of parentheses does that (as well as grouping the alternatives). The first set of parentheses is non-capturing, by the way, thanks to the ? as the first character within them.)
Anyway, having captured the text you want, you will refer to that capture group in your replacement expression as \\1 . That's backslash-one.
If you had multiple capturing groups in your regex, then you could refer to the second one with \\2 , and so on.
If you have nested capturing groups, then you count them in the order of their opening parenthesis. So in ((foo)bar) , for example, \\1 would be "foobar" and \\2 would just be "foo".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM