简体   繁体   English

用正则表达式完全匹配一次字符

[英]Match a character exactly once with regex

How can I match a character exactly once with a regex in Java? 如何在Java中将一个字符与正则表达式完全匹配一次? Let's say I want to look for strings which contain exactly one time the digit 3, and it doesn't matter where it is. 假设我要查找的字符串恰好包含数字3的一倍,并且在哪里都无所谓。

I tried to do this with ".*3{1}.*" but obviously this will also match "330" as I specified with the period that I don't care what character it is. 我尝试使用“。* 3 {1}。*”进行此操作,但是很明显,这也将与我指定的“ 330”匹配,因为我不在乎它是什么字符。 How can I fix this? 我怎样才能解决这个问题?

^[^3]*3[^3]*$

Match (not three), then three, then (not three). 匹配(不三个),然后匹配三个,然后(不匹配三个)。

Edit: Adding ^ and $ at beginning and end. 编辑:在开始和结束处添加^$ This will force the regex to match the whole line. 这将迫使正则表达式匹配整行。 Thanks @Bobbyrogers and @Mindastic 谢谢@Bobbyrogers和@Mindastic

A non-regex solution: 非正则表达式解决方案:

int index = s.indexOf('3');
boolean unique = index != -1 && index == s.lastIndexOf('3');

Basically the character is unique if the first and last occurrences are at the same place and exist in the string (not -1). 基本上,如果第一次出现和最后一次出现在同一位置并且存在于字符串中(不是-1),则该字符是唯一的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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