简体   繁体   English

正则表达式通过开始子字符串替换单词并以 Java 中的点或空格结尾

[英]Regex to replace a word by starting sub String and ends with dot or space in Java

I need to replace #id in my css String, let say I have id as #id_123456 as id in my css I have to replace it with #id_7891011.我需要在我的 css 字符串中替换#id,假设我在我的 css 中有 id 作为#id_123456 作为 id 我必须用#id_7891011 替换它。 I know my id starts with #id_ and it can end with./space/+/>.我知道我的 id 以 #id_ 开头,并且可以以 ./space/+/> 结尾。 I am trying to do regex to replace all my old id with new Id.我正在尝试使用正则表达式将我所有的旧 ID 替换为新 ID。 My regex looks like.我的正则表达式看起来像。

(.* ?)(#id_[a-zA-Z0-9 ]+[.^\S])(.*)

It working for the start condition but not end by the space or dot it replaces the whole line.它适用于开始条件,但不以空格或点结束,它会替换整行。 Any help would be appreciated.任何帮助,将不胜感激。

Use a lookahead:使用前瞻:

#id_[a-zA-Z0-9\s]+(?=[.\s+>])
                  |_________|

See proof .证明 The (?=[.\s+>]) will make sure matching stops before . (?=[.\s+>])将确保匹配在. /whitespace/ + / > . /空白/ + / >

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

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