首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >正则表达式需要查找仅包含[st||nd||rd||th]的数字

正则表达式需要查找仅包含[st||nd||rd||th]的数字
EN

Stack Overflow用户
提问于 2014-08-12 16:56:33
回答 4查看 1.4K关注 0票数 0

我需要一个正则表达式来查找包含这些单词的数字:

代码语言:javascript
运行
复制
 1st, 2nd, 3rd, 4th, 5th.

从以下文本中:

代码语言:javascript
运行
复制
 <xps:span class="ref_sn">Huang</xps:span></xps:span> <xps:span
 class="ref_au"><xps:span class="ref_gn">K.</xps:span> <xps:span
 class="ref_sn">Chingin</xps:span></xps:span> <xps:span
 class="ref_au"><xps:span class="ref_gn">R.</xps:span> <xps:span
 class="ref_sn">Zenobi</xps:span> 1st</xps:span> <xps:span
 class="ref_atitle">Real<span class='xps_ndash'>&#8211;iou</span>time,
 on<span class='xps_ndash'> 2nd &#8211;iou</span>line 4th monitoring of
 organic chemical reactions using 3rd extractive electrospray
 ionization tandem mass 5th spectrometry</xps:span> <xps:span
 class="ref_jtitle">Rapid Commun. Mass Spectrom.</xps:span>

我需要将这些字母表转换为sup。

我正在使用这个正则表达式,但它不起作用。

代码语言:javascript
运行
复制
(\b)(\d+([st|nd|rd|th]+)\b)
EN

回答 4

Stack Overflow用户

发布于 2014-08-12 16:59:00

正则表达式也称为字符集,您可以告诉正则表达式引擎只匹配几个字符中的一个。

代码语言:javascript
运行
复制
[st|nd|rd|th]            any character of: 
                       's', 't', '|', 'n', 'd',
                       '|', 'r', 'd', '|', 't', 'h'

您需要使用(...)而不是[...]

你可以试试

代码语言:javascript
运行
复制
\d+(?=st|nd|rd|th)

这是demo

示例代码:

代码语言:javascript
运行
复制
String str = "1st, 2nd, 3rd, 4th, 5th.";
Pattern p = Pattern.compile("\\d+(?=st|nd|rd|th)");
Matcher m = p.matcher(str);
while (m.find()) {
    System.out.println(m.group());
}

输出

代码语言:javascript
运行
复制
1
2
3
4
5

您可以使用捕获组修改您的正则表达式,如下所示,并获得所需的匹配组:

代码语言:javascript
运行
复制
Pattern p=Pattern.compile("(\\d+)(st|nd|rd|th)");
Matcher m=p.matcher(str);
while(m.find()){
    System.out.println(m.group(1));
}
票数 5
EN

Stack Overflow用户

发布于 2014-08-12 16:58:59

只需要尝试一下:

只需尝试使用以下正则表达式:

代码语言:javascript
运行
复制
(\d+(?:st|nd|rd|th))

demo

票数 1
EN

Stack Overflow用户

发布于 2014-08-12 17:03:00

只是稍微修改一下你的代码:

代码语言:javascript
运行
复制
public static void main(String[] args) {
    String s = "Huang K. Chingin R. Zenobi 1st Real–ioutime, on 2nd –iouline 4th monitoring of organic chemical reactions using 3rd extractive electrospray ionization tandem mass 5th spectrometry Rapid Commun. Mass Spectrom";
    Pattern p = Pattern.compile("\\d+(?=st|nd|rd|th)");
    Matcher m = p.matcher(s);
    while (m.find()) {
        System.out.println(m.group());
    }
}

O/P:

代码语言:javascript
运行
复制
1
2
4
3
5
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25260093

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档